javascript convert date string to date - javascript

How do I convert a string like this back to a date object?
"Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)"
Is there a more native way to store dates in javascript?

I've tested this in IE7, IE8, IE9, chrome, and firefox 6:
new Date('Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)');
and it works.

http://www.w3schools.com/jsref/jsref_obj_date.asp provides some insight, just package it up and send it through and youll find all sorts of conveniance provided.
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

If your dates will always be in a standard format (for sure), you could split into an array based on the space character and then create a date object from the items in the array.
Maybe not best approach but if your addresses are standardized, it might not be too bad, and probably pretty fast to implement/execute. :)

Date.parse(your date string) returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. Store this number. When you want to display a date, use new Date(theNumber). Example:
var milliseconds = Date.parse("Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)");
// milliseconds == 1313694835000
alert(new Date(milliseconds));
// alerts Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)

The Date object is quite accommodating so you can just use the string directly in a new object.
http://www.w3schools.com/js/js_obj_date.asp
new Date("Thu Aug 18 2011 15:13:55 GMT-0400 (Eastern Daylight Time)")
I say this a lot but when it comes to things like this, it's always awesome to experiment in the browser console and really get a feel for what the objects are capable of doing.. happy coding!

Related

How to convert time to specific string?

I'm working with a date that looks like this:
Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)
and I'm trying to convert it to this:
2019-02-04T15:57:02.000Z
but for some reason my code always adds 7 hours and ends up being like this:
"2019-02-05T22:57:02.000Z"
Can anyone tell me what I'm doing wrong? Thanks a lot in advance!
Here's my code:
new Date(myTime as string).toISOString();
I'd use Moment.js, which is a decent date parsing and formatting library. To get what you're looking for, you'd use a statement like:
console.log(moment
.parseZone(
"Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)",
"ddd MMM DD YYYY HH:mm:ss 'GMT'ZZ") // the format of the string presented
.local()
.format('YYYY-MM-DDTHH:mm:ss')); // the format of the output
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
I've broken the single line out into parts so it's a bit easier to read. A few notes:
parseZone allows you to parse the "-0700" from the string.
local converts the date from the parsed time zone to the current time zone
format formats the date.
The format topic has a list of the formatting tokens used.
The Parse > String + Format topic lists the parsing tokens (which are the same as the formatting tokens for the most part).
Note that the output does not have a "Z" at the end; this is important because without the "Z", it is a local date. With the "Z" you are are actually specifying a date and time that is 7 hours earlier than the one you've been given.
I'm not sure how to get this as a one-liner, but this is one way:
var time = new Date('Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)')
new Date(time.setHours(time.getHours() + 7)).toISOString()
"2019-02-05T12:57:02.000Z"
Your code is not adding hours to the input date. What is happening is that your date string is using a particular timezone GMT-0700 (Mountain Standard Time) and the time zone used in new Date().toISOString() is UTC GMT+0000 (UTC). So when in the Mountain Standard Time timezone is Mon Feb 04 2019 15:57:02, in the UTC timezone is actually 2019-02-05T22:57:02.000Z. There are your seven hours from GMT-0700 to GMT+0000.
EDITED
If you don't really care about time zones and want to obtain 2019-02-04T15:57:02.000Z from Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time) you could just strip everything after GMT to let new Date() think it is an UTC date.
var timeString = 'Mon Feb 04 2019 15:57:02 GMT-0700 (Mountain Standard Time)';
new Date(timeString.substr(0, timeString.indexOf('GMT') + 3));
2019-02-04T15:57:02.000Z

JS Date GMT + or - seems to work the wrong way round...?

Please see the code example below from Google Chrome:
new Date('Thu Jul 27 2017 13:10:42 GMT-0500')
Result: Thu Jul 27 2017 19:10:42 GMT+0100 (BST)
new Date('Thu Jul 27 2017 13:10:42 GMT+0500')
Result: Thu Jul 27 2017 09:10:42 GMT+0100 (BST)
I would read the first date current time as being 13:10 which is -0500 hours off from GMT but the result it gives is +5 hours in the future +1 hour BST. In a similar vein the second date works the opposite way being +0500 hours off but returning -5 hours in the past +1 BST.
Firefox works in a similar way but it seems without the BST:
new Date('Thu Jul 27 2017 13:10:42 GMT-0500');
Date 2017-07-27T18:10:42.000Z
new Date('Thu Jul 27 2017 13:10:42 GMT+0500')
Date 2017-07-27T08:10:42.000Z
IE Edge gives me these results:
new Date('Thu Jul 27 2017 13:10:42 GMT-0500')
Thu Jul 27 2017 19:10:42 GMT+0100 (GMT Summer Time)
new Date('Thu Jul 27 2017 13:10:42 GMT+0500')
Thu Jul 27 2017 09:10:42 GMT+0100 (GMT Summer Time)
Can anyone help throw some light on this please?
EDIT - this is not a duplicate of 'Why does Date.parse give incorrect results?' because I am not using the parse() method explicitly.
Please note: I am trying to create a date object that is not in the same timezone as my browser.
If this is not possible I might have to solve my current problem with some basic math (current time +/- the timezone required) - shame if I cannot do this with a native JS Date object.
The default conversion of a Date instance to a string gives you the date and time in terms of the local timezone. If you're doing it in the browser console, you can't even rely on that, because the console itself is free to do whatever it wants. Firefox's console seems to extract the UTC representation; if you call
new Date('Thu Jul 27 2017 13:10:42 GMT-0500').toString()
instead you get the local time.
Dates are based on the idea of UTC timestamps and the notion that local time is generally important. Creating a date from a string gives you a timestamp meaningful (well, as meaningful as possible) for the string, but subsequently the Date instance is by default treated as something relevant to the local context. You can always use the UTC APIs to extract the UTC time if you want.
This question seems to stem from unfamiliarity either with how date strings are parsed by the built–in parser or with how they are formatted by various built–in toString methods.
The same parser is used by Date.parse and the Date constructor, it doesn't matter which is used in terms of how the string is parsed to a time value. The only difference between the two is that Date.parse returns the time value as a number, whereas the Date constructor uses the time value to create a Date instance (which is the only value that a Date instance holds).
The time value itself is milliseconds since 1970-01-01T00:00:00Z, so has no time zone (and means Date instances are effectively UTC). The value returned by getTimezoneOffset and the timezone displayed in toString methods (if there is one) is from the host system, it's not a property of Date instances or the Date constructor.
The timestamp pairs in your question represent exactly the same moment in time, but in different time zones.
Thu Jul 27 2017 13:10:42 GMT-0500 is Thu Jul 27 2017 18:10:42 GMT.
Thu Jul 27 2017 19:10:42 GMT+0100 (BST) is also Thu Jul 27 2017 18:10:42 GMT.
The value returned by Date.prototype.toString is entirely implementation dependent. When you send a date to output, the host may use any method it likes to represent the Date and may format it any way it wants. In the above, it seems the host timezone (UTC+0100) has been used with the default toString, which may return a differently formatted string in different implementations.
However, recent browsers seem to have settled on RFC 2822 format. Other methods that typically return different formats are toISOString and toLocaleString (noting that all three methods could return an ISO 8601 format string and be consistent with the ECMA-262, though I don't know of any implementations that do).
The next two dates also represent exactly the same moment in time:
Thu Jul 27 2017 13:10:42 GMT+0500 is Thu Jul 27 2017 08:10:42 GMT
Thu Jul 27 2017 09:10:42 GMT+0100 (BST) is also Thu Jul 27 2017 08:10:42 GMT
Again, the host timezone has been used to generate the output string.
As for "Firefox works in a similar way but it seems without the BST", see above. ECMA-262 only requires the the format be convenient and human readable. In this case, the browser developers have chosen to use an ISO 8601 format with no offset (i.e. UTC+0000).
So:
Thu Jul 27 2017 13:10:42 GMT-0500 is Thu Jul 27 2017 18:10:42 GMT+0000
2017-07-27T18:10:42.000Z is also Thu Jul 27 2017 18:10:42 GMT+0000
The choice not to use a timezone offset is entirely up to the browser developers and is consistent with ECMA-262.
If your issue is with how date strings are parsed, the duplicate is Why does Date.parse give incorrect results?. If it's with how dates are formatted, the duplicate is Where can I find documentation on formatting a date in JavaScript? The answers to those two questions should answer any issue raised in the OP.

New date to string shows as day before because of time zone

How can I display a date to behave like that day regardless of the users time-zone?
>>> new Date('2013-09-17')
Date {Mon Sep 16 2013 20:00:00 GMT-0400 (Eastern Standard Time)}
I'm trying to use the jquery datepicker formater, however when I pass the date object it's off by a day.
How can I make sure that the users timezone is disregarded?
OK, I split the string and passed them as parameters for my expected result.
>>> d = '2013-09-17'.split('-'); new Date(d[0],d[1]-1,d[2]);
Date {Thu Oct 17 2013 00:00:00 GMT-0400 (Eastern Standard Time)}

Reformat a date string [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 8 years ago.
I am working towards formatting my date and time from MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME) to look like MON APR 08 2013 01:01:01. Although I am having no luck with everything I have tried. Can someone shed a little light. Below is the last piece of code I have tried. Thanks.
var date = new Date(parseInt(data[0].published.substr(6)));
var time = new Date(date.toLocaleDateString());
If you can, the best practice would probably be to format the date server-side, or at least present a more universally useful date (like a UNIX timestamp) instead of the formatted string.
However, if changing the server-side output is not an option, you can use the javascript date object. I see you've tried that, but you're not using the date object's constructor properly:
var dateString = 'MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME)';
var dte = new Date(dateString);
document.write(dte.toDateString()); // output: Mon Apr 08 2013
Try it: http://jsfiddle.net/BvLkq/
If you need to reconstruct the time, you can use toLocaleDateString (docs) to pass a locale or format string, or you can build one up by hand using the getHours() (etc) functions .
Documentation
Date object on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Just use a simple regex.
var str = 'MON APR 08 2013 00:00:00 GMT-0400 (EASTERN DAYLIGHT TIME)';
console.log(str.replace(/(.*\d{2}\:\d{2}\:\d{2}).*$/, '$1'));
// outputs MON APR 08 2013 00:00:00

Changing Date object

I'm trying to return a date function, from
Mon Jul 30 2012 10:57:56 GMT 0100 (GMT Daylight Time)
to
30 July 2012 10:57:56
Tried out most of the date functions, but still no answer/format.
Do not invent a bicycle, use library for this: http://blog.stevenlevithan.com/archives/date-time-format

Categories