How to convert a string to date format in JavaScript [duplicate] - javascript

This question already has answers here:
JavaScript datetime parsing [duplicate]
(2 answers)
Closed 8 years ago.
How do I convert a string to date using JavaScript?
Example:
Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)
I want to convert it to:
YYYY-mm-dd H:i:s

The Date constructor accepts strings representing dates, example :
var date = new Date("Wed May 21 2014 02:40:00");
alert(date.getDate()); // 21
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

You must parse and format the string with the Date Class with the methods:
Date.parse()
Date.toISOString()
For example:
var text = "Wed May 21 2014 02:40:00 GMT+0600 (Central Asia Standard Time)";
var date = new Date(Date.parse(text));
var formatedText = date.toISOString();
console.log(formatedText );
If you need a custom format, try to use a custom formater, for example:
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
function toCustom(date) {
return date.getUTCFullYear() +
'-' + pad( date.getUTCMonth() + 1 ) +
'-' + pad( date.getUTCDate() ) +
' ' + pad( date.getUTCHours() ) +
':' + pad( date.getUTCMinutes() ) +
':' + pad( date.getUTCSeconds() );
};
These may be very useful:
Date.parse()
Date.prototype.toISOString()

You can even translate it with my plugin. It's as simple as:
$(selector).setDate({format: "+Y-+m-+d +H:+ii:+ss"; date: 'Wed May 21 2014 02:40:00'});
https://github.com/Masquerade-Circus/setDate.js
You can pass a date object too, no need to get the string of the date.

Related

Why the toISOString() applied on a Date object generate a wrong time section converting a date into a string?

I am going crazy with this Date to String conversion into a TypeScript project:
I have this function performing my conversion:
fromDateToString(date: Date) : String {
let dateAsString = date.toISOString().substr(0, 19)
console.log(dateAsString);
return dateAsString;
}
As you can see it take a Date object containing the following value:
Wed Feb 08 2017 07:00:00 GMT-0800 (Ora standard del Pacifico USA)
and, in theory it have to convert this date in the following string format:
2017-02-08T07:00:00"
But I am finding a strange behavior on the time !!! The generated string is not the previous one but it is:
2017-02-08T15:00:00"
The generated time section is not 07:00:00 but it is 15:00:00
Why? What is wrong? What am I missing? How can I fix this issue?
The value isn't wrong; you're disregarding the timezone. toISOString returns a string written in UTC with Z at the end saying it's in UTC. You're stripping off the part of the string saying what timezone it's in.
If you like, you can get that string in local time instead by subtracting the timezone offset:
function fromDateToString(date/*: Date*/)/* : String*/ {
date = new Date(+date);
date.setTime(date.getTime() - (date.getTimezoneOffset() * 60000));
let dateAsString = date.toISOString().substr(0, 19);
return dateAsString;
}
console.log(fromDateToString(new Date()));
Just beware that your code using that string handles it as a local time, not UTC.
2017-02-08T15:00:00 -> this is UTC date (ISO) [UTC has 0:00 offset]
2017-02-08T07:00:00 -> this is GMT-0800
so if we convert 2017-02-08T07:00:00 to UTC we need to add 8:00 hours so 7 + 8 = 15 so its giving 2017-02-08T15:00:00
You directly cannot ignore timezone offset without adding/subtracting.
That happens because the EcmaScript algorithm for generating an ISO string always generates it with the UTC+0 timezone. You don't need (and shouldn't) modify the Date object. Here's an algorithm to get a ISO string with the local timezone:
let toLocalISOString;
{
const pad = function pad(str) {
return String(str).padStart(2, "0");
}
toLocalISOString = function toLocalISOString(date) {
const tzOffset = date.getTimezoneOffset(),
tzPlus = tzOffset >= 0;
return date.getFullYear() +
'-' + pad(date.getMonth() + 1) +
'-' + pad(date.getDate()) +
'T' + pad(date.getHours()) +
':' + pad(date.getMinutes()) +
':' + pad(date.getSeconds()) +
'.' + (date.getMilliseconds() / 1000).toFixed(3).slice(2, 5) +
(tzPlus ? "+" + pad(tzOffset / 60) : "-" + pad((tzOffset / 60).toString().slice(1))) +
":" + pad((tzOffset % 60).toFixed(0));
};
}

How to Convert a Date String to UTC date using Javascript? [duplicate]

This question already has answers here:
How to convert a Date to UTC?
(34 answers)
Closed 8 years ago.
I have a date string CStartDate as '3/23/2014' that I am getting from siebel side.I need to convert it to UTC time zone where timeoffset becomes zero.I have tried something like this:
var a = CStartDate.split('/');
var c = a[0];
a[0] = a[1];
a[1] = c;
var tacStartDate = new Date(a[2],parseInt(a[1], 10) - 1,a[0]);
alert(tacStartDate);
This alert returns as 'Sun Mar 23 2014 00:00:00 GMT+0530 (India Standard Time)', but I don't want that offset GMT+0530 (India Standard Time), rather I want it only to be 'Sun Mar 23 2014 00:00:00 GMT+0000'.I want this as a date object which will be indicating date of GMT, not any other location. How can I achieve that?
Thanks in advance.
try toISOString() on the Date object. If using less than ECMAScript 5, there is a polyfill for the function
if ( !Date.prototype.toISOString ) {
( function() {
function pad(number) {
if ( number < 10 ) {
return '0' + number;
}
return number;
}
Date.prototype.toISOString = function() {
return this.getUTCFullYear() +
'-' + pad( this.getUTCMonth() + 1 ) +
'-' + pad( this.getUTCDate() ) +
'T' + pad( this.getUTCHours() ) +
':' + pad( this.getUTCMinutes() ) +
':' + pad( this.getUTCSeconds() ) +
'.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice( 2, 5 ) +
'Z';
};
}() );
}
There is an UTC method of Date. It should be as simple as:
new Date(Date.UTC(a[2],parseInt(a[1], 10) - 1,a[0]));

ISO 8601 not retaining timezone?

i am using the timeago Jquery plugin to output strings like "5 mins ago" etc.
The plugin uses ISO 8601 date format.
I have a Date object which looks like this in console:
Sat Jun 15 2013 07:16:23 GMT+0530 (India Standard Time)
To convert it into ISO 8601 I do this:
date = date.toISOString();
Now it looks like this in the console:
2013-06-15T01:46:23Z
Apparently, the time zone has been set to UTC ( Z stand for UTC ).
This messes up with timeago plugin as everything is now in UTC, not in the local timezone.
I tried this:
Date.prototype.toISOStringfix = function() {
function pad(n) { return n < 10 ? '0' + n : n }
return this.getUTCFullYear() + '-'
+ pad(this.getUTCMonth() + 1) + '-'
+ pad(this.getUTCDate()) + 'T'
+ pad(this.getUTCHours()) + ':'
+ pad(this.getUTCMinutes()) + ':'
+ pad(this.getUTCSeconds()) + 'Z';
};
However, I get the same result.
Why does this happen? How can I fix it?

Javascript date formatting Fri Jun 21 00:00:00 UTC+0100 2013 to iso 8601 (2013-06-21)

Please advise:
Is there a way without regex or string replaces and so forth to convert a simple date such as:
Fri Jun 21 00:00:00 UTC+0100 2013
To a ISO8601 formatted date yy-mm-dd?
PS: 8601 date only, not date time.
Use moment.js http://momentjs.com/
moment(new Date(), "YYYY-MM-DD HH:mm Z");
or:
var date = moment("Fri Jun 21 00:00:00 UTC+0100 2013");
moment("Fri Jun 21 00:00:00 UTC+0100 2013", "YYYY-MM-DD HH:mm Z");
You can parse it and format it very easily whatever way you want http://momentjs.com/docs/ it is compatible with ISO-8601 dates for parsing as well.
Yes !
the date function in javascript.
var d = new Date("Fri Jun 21 00:00:00 UTC+0100 2013")
alert( d.getFullYear() + '-' + d.getUTCMonth() + '-' + d.getUTCDay())
2 lines of code :)
more info here : http://www.w3schools.com/jsref/jsref_obj_date.asp
Without regexes or string replaces? Yes, assuming that the format is fixed you could use .slice() and/or .substr() to extract the particular bits you need and rearrange them (unless such methods fall into your category of "and so forth"):
var input = "Fri Jun 21 00:00:00 UTC+0100 2013";
var year = input.slice(-4),
month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(input.substr(4,3))+1,
day = input.substr(8,2);
var output = year + '-' + (month<10?'0':'') + month + '-' + day;
Or you could go ahead and get silly with a regex replace:
var output = input.replace(/^[^\s]+\s([^\s]+)\s(\d+)\s.*(\d{4})$/,function(m,p1,p2,p3) {
var month = ['Jan','Feb','Mar','Apr','May','Jun',
'Jul','Aug','Sep','Oct','Nov','Dec'].indexOf(p1)+1;
return p3 + '-' + (month<10?'0':'') + month + '-' + (p2.length===1?'0':'') + p2;
});
Of course you'd probably want to wrap such code in a reformatDate() method.
(For a "simple" reformatting of a date string, the Date object and its methods aren't particularly helpful unless the starting format is one recognised by Date.parse().)
Why dont you try to use the get functions, like getDate(), getMonth(), etc. For example:
var today = new Date();
var d1 = new Date();
alert(d1);
var date = d1.getDate();
var month = d1.getMonth() + 1;
var year = d1.getFullYear();
Then configure the string the way you want it to appear...!

Date() converts certain date strings to local time

I'm trying to compare two date strings for equality by wrapping them with the Date() object. I live in Seattle and for some reason, the second date string is converted to PST and then rendered in GMT, resulting in the below:
new Date("January 1, 2012")
>>> Sun Jan 01 2012 00:00:00 GMT-0800 (PST)
new Date("2012-01-01")
>>> Sat Dec 31 2011 16:00:00 GMT-0800 (PST)
Try the above in the chrome console and you should get the same results.
How do I get Date to evaluate the second statement as GMT instead of PST?
Do not use the Date object to parse date strings, it is specified as implementation dependent in ECMAScript ed 3 and doesn't work consistently across browsers. One format of ISO8601 date string is specified in ES5, but that doesn't work consistently either. Manually parse the string.
A couple of functions to convert to and from UTC ISO8601 strings:
if (!Date.prototype.toUTCISOString) {
Date.prototype.toUTCISOString = function() {
function addZ(n) {
return (n<10? '0' : '') + n;
}
function addZ2(n) {
return (n<10? '00' : n<100? '0' : '') + n;
}
return this.getUTCFullYear() + '-' +
addZ(this.getUTCMonth() + 1) + '-' +
addZ(this.getUTCDate()) + 'T' +
addZ(this.getUTCHours()) + ':' +
addZ(this.getUTCMinutes()) + ':' +
addZ(this.getUTCSeconds()) + '.' +
addZ2(this.getUTCMilliseconds()) + 'Z';
}
}
if (!Date.parseUTCISOString) {
Date.parseUTCISOString = function fromUTCISOString(s) {
var b = s.split(/[-T:\.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
}
var s = '2012-05-21T14:32:12Z'
var d = Date.parseUTCISOString(s);
alert('Original string: ' + s +
'\nEquivalent local time: ' + d +
'\nBack to UTC string: ' + d.toUTCISOString());
Taking robg's advice you might look at DateJS or moment.js
That's because of your time zone, you are 8:00 hours late to the "2012-01-01", so its showing like that, for me i got this
new Date("January 1, 2012")
Sun Jan 01 2012 00:00:00 GMT+0530 (IST)
new Date("2012-01-01")
Sun Jan 01 2012 05:30:00 GMT+0530 (IST)

Categories