Format JSON DateTime - javascript

I currently have all my dates being returned with the letter T in my JSON Strings. EX: 2019-02-03T06:48:07. Is there a way to change the JSON String to return as 02-03-2019 06:48:07?
I am also using javascript to load the dates currently into a data table.

You can convert your string into a Date object and then format it like this:
let jsonString = "2019-02-03T06:48:07";
// You should set your own timezone and options.
console.log(new Date(jsonString).toLocaleString('en-US', {hour12: false}))
For more information, visit: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

The T is there because this is a standard ISO 8601 format. It makes it very easy to parse on the client side:
var myDate = new Date('2019-02-03T06:48:07')
With myDate you can then do whatever formatting you wish. Assuming you have another function to handle leading zeros, that could be something like:
var myFormattedDate = padLeft(myDate.getMonth() + 1, '0') + '-' +
padLeft(myDate.getDay(), '0') + '-'
myDate.getFullYear() + ' ' +
// etc
Note that your timestamp lacks any timezone information. With this code it will be interpreted on the client side in whatever the local timezone of the user is. If it is UTC time, then you can correct for this by adding either 'Z' or '+00:00' onto the timestamp before parsing in the Date constructor.
If you are able to add a library to assist, this all becomes much easier with moment.js:
myFormattedDate = moment('2019-02-03T06:48:07').format('MM/DD/YYYY HH:mm:ss');

Related

Convert time format string with moment.js

I am getting a date string in format '2020-01-22T19:52:13.180Z' from an API. I am using momentjs library for datetime manipulation. But I am not able to find a format in momentjs to convert the above string into valid javascript date or moment object. [I have no control over the response returned from the API].
You can get javascript date object by using the Date constructor itself.
new Date("2020-01-22T19:52:13.180Z").
You can format Date manually as you want. Refer to the following code.
let current_datetime = new Date("2020-01-22T19:52:13.180Z")
let formatted_date = current_datetime.getDate() + "-" + (current_datetime.getMonth() + 1) + "-" + current_datetime.getFullYear()
console.log(formatted_date)

How to get date from js in correct format? Month and days get reversed

I am calling an ajax for getting some values for editing data.
As a part of my object, I am sending the date field.
My problem is that when I receive the date value in the controller, date format is wrong - my dates and months are reversed. And because of that I can't compare them where I need to.
But my months and days are reversed. For an example , instead of 3rd October, it returnes 10th of March.
How to fix this?
I am sending the date field from js in a object like this:
ExamsDataU = {
classId: classIdValue,
date: dateValue
};
And in my controller I tried:
DateTime dateToCheck = Convert.ToDateTime(dto.Date);
The first thing you should know is date parsing with Convert.ToDateTime() depends to the current culture used in server (you may check it using CultureInfo.CurrentCulture property). You can try one of these methods to parse JS date format properly inside controller action method:
1) Using DateTime.ParseExact()/DateTime.TryParseExact() with custom format
On this way it is necessary to specify date format before parsing date:
// specify custom format
string dateFormat = "dd-MM-yyyy";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture);
2) Using DateTime.ParseExact()/DateTime.TryParseExact() with ISO 8601 format
Use date: dateValue.toISOString(); to convert JS date into ISO 8601 format and then convert it:
// specify ISO format
string dateFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind);
This way is better than the former because no need to write additional date representation code in client-side, also you can adjust date representation to local time if necessary.
Notes:
a) For specified culture, you can try CultureInfo.GetCultureInfo():
var culture = CultureInfo.GetCultureInfo(CultureInfo.CurrentCulture.Name);
DateTime dateToCheck = DateTime.ParseExact(dto.Date, dateFormat, culture);
b) You can use if condition to check if the date string is valid when using DateTime.TryParseExact():
DateTime dateToCheck;
if (DateTime.TryParseExact(dto.Date, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateToCheck))
{
// do something
}
Try this
var date = new Date('2014-01-06');
var newDate = date.toString('dd-MM-yy');
or
var dateAr = '2014-01-06'.split('-');
var newDate = dateAr[1] + '-' + dateAr[2] + '-' + dateAr[0].slice(-2);
console.log(newDate);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Date and time parsing in JavaScript

I have a question that I am trying to solve for whole day.
I have Date and Time from Oracle DB that is shown on html page. I have jstl date formatter that has special pattern to show it. Let's take an example 09.05.2017 17:35 +0500 and pattern MM.dd.yyyy HH:mm Z. And I am getting it as String with jQuery . The first case: how to convert it to Date type without any changes. I tryed var date = new Date('09.05.2017 17:35 +0500') but if I have another time zone I'll recieve another UTC and time(hour) or maybe month etc.
Second: how to convert this time to UTC+0300.
I know one solution of this cases, but I think it's not easy. As I have constant pattern of Date, I can always parse the string and to write huge logic for solving second case. I am bad in JS and will be grateful for solution.
Regarding the parsing question, that is answered at Why does Date.parse give incorrect results? The bottom line is that you should parse the string manually and not rely on the built-in parser. A library can help, but if you only have one or two formats to deal with, writing your own parser isn't too difficult.
As for presenting time in a particular timezone, the same advice applies. If you always want UTC+0300, then start by knowing that javascript Dates are always UTC internally and have UTC methods to access those values. So you just change the UTC time by the required offset and format the date as required.
For formatting, see Where can I find documentation on formatting a date in JavaScript?
An example of adjusting the timezone:
// Return a string for UTC+0300 for the supplied date
// in dd-mm-yyyy hh:mm:ss format
function getUTC03(date) {
// Helper to pad with leading zero
function z(n){return ('0'+n).slice(-2)}
// Copy the date so don't affect original
var d = new Date(+date);
// Set UTC time to required offset
d.setUTCHours(d.getUTCHours() + 3);
// Format using UTC methods
return z(d.getUTCDate()) + '-' +
z(d.getUTCMonth()+1) + '-' +
d.getUTCFullYear() + ' ' +
z(d.getUTCHours()) + ':' +
z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' +
'+0300';
}
console.log('Currently at +0300 it\'s ' + getUTC03(new Date()));
However, many places observe daylight saving. To adjust for that, a library is helpful. You just need to provide a location for which the offset can be determined for any particular date and time. Again, there are many questions here about that too.

Convert Date String(yymmdd) to Date Object in JS

I have a date string in "yymmdd" format i want to convert it into date object in JS
the input string is "161208"
I have tried code below
var mydate = new Date(InputDate);
but it says invalid date.
Here is the fiddle
https://jsfiddle.net/4ry0hL4t/
the basic need is that, I have a date string in "yymmdd" format and i have to convert it to different date formats like ("yyyy/mm/dd, yy-mm-dd","yy/mm").
Check my answer.
Basically you first need to give a proper format to your string. You can either do it manually or use moment.js.
stringFormat = moment(dateObject).format("YYYY-MM-DDTHH:mm:ss");
date = new Date(stringFormat);
This is also really helpful to understand how the different string formats are compatible with different browsers.
I'm not sure if this is what you're after?
var s = '161208';
var dt = new Date('20' + s.substring(0, 2) + '-' + s.substring(2, 4) + '-' + s.substring(4));

Regular Expression Pattern match for Date

I am trying to extract the date from the following object (that has been stringified.)
I am new to regular expressions, and not sure how to go about it.
I tried /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/gmi -> but it didnot work.
{"Date":"2016-05-16","Package Name":"com.myapp.mobile","Current Device Installs":"15912","Daily Device Installs":"41","Daily Device Uninstalls":"9","Daily Device Upgrades":"3","Current User Installs":"12406","Total User Installs":"23617","Daily User Installs":"27","Daily User Uninstalls":"8"}
Don't use a Regex here.
Do JSON.parse(str).Date, unless there is a really good reason not to (you haven't stated one in your question)
If you want to turn the string "2016-05-16" into 3 variables for Year, Month and day (without using a date library), I'd just use .split():
dateArray = "2016-05-16".split("-")
var year = dateArray[0], month = dateArray[1], day = dateArray[2];
Your regex matches fine, just don't use the /gmi flags
"2016-05-16".match(/^(\d{4})\-(\d{1,2})\-(\d{1,2})$/)
You can make it a bit simpler yet..
"2016-05-16".match(/(\d{4})-(\d{2})-(\d{2})/)
But, you really should be using a library for this, like moment.js, or at least Date which will work fine because this ISO-8601.
const date = new Date("2016-05-16");
date.getYear();
As suggested in comments, you can get the date by parsing the JSON (trimmed in the following for convenience):
var s = '{"Date":"2016-05-16","Package Name":"com.myapp.mobile"}';
var dateString = JSON.parse(s).Date;
document.write(dateString);
If you want a Date object, you can then parse the string. Note that using either the Date constructor or Date.parse for parsing strings is not recommended due to browser inconsistencies. Manually parsing an ISO date is fairly simple, you just need to decide whether to parse it as local or UTC.
Since ECMA-262 requires the date–only ISO format to be parsed as UTC, the following function will do that reliably (and return an invalid date for out of range values):
/* Parse an ISO 8601 format date string YYYY-MM-DD as UTC
** Note that where the host system has a negative time zone
** offset the local date will be one day earlier.
**
** #param {String} s - string to parse
** #returs {Date} date for parsed string. Returns an invalid
** Date if any value is out of range
*/
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(Date.UTC(b[0], b[1]-1, b[2]));
return d && d.getMonth() == b[1]-1? d : new Date(NaN);
}
var d = parseISODate('2016-05-16');
document.write('UTC date: ' + d.toISOString() + '<br>' +
'Local date: ' + d.toString());

Categories

Resources