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
Related
This question already has answers here:
Ambiguous behavior of javascript new Date() constructor for same different formatted string
(3 answers)
Closed 2 months ago.
I am getting an odd behavior if I pass the Date constructor just a date string. Example:
<div>Date 1: <span id="mydate1"></span></div>
<div>Date 2: <span id="mydate2"></span></div>
<div>Date 3: <span id="mydate3"></span></div>
<script>
document.getElementById("mydate1").innerHTML = (new Date("2022-06-28 20:32:00")).toString();
document.getElementById("mydate2").innerHTML = (new Date("2022-06-28")).toString();
document.getElementById("mydate3").innerHTML = (new Date("2022-06-28 00:00:00")).toString();
</script>
This results in the following:
Date 1: Tue Jun 28 2022 20:32:00 GMT-0400 (Eastern Daylight Time)
Date 2: Mon Jun 27 2022 20:00:00 GMT-0400 (Eastern Daylight Time)
Date 3: Tue Jun 28 2022 00:00:00 GMT-0400 (Eastern Daylight Time)
Date 1 works as I would expect. But why are Date 2 and 3 different? With just a date string, it seems to be inferring the date is in UTC, where as with a time field it seems to assume it is in my locale time.
Any thoughts? I can work around it by appending the 00:00:00 text.
It is explained in the documentation of Date constructor, when the argument is a date string:
Date-only strings (e.g. "1970-01-01") are treated as UTC, while date-time strings (e.g. "1970-01-01T12:00") are treated as local.
How can I get Fri Oct 25 2019 from a date object as below?
Fri Oct 25 2019 15:27:01 GMT+0530 (India Standard Time)
Use the toDateString() function from JavaScript.
let d = new Date();
// note : the actual display output depend on your browser/system settings (locale)
console.log(d.toString());
console.log(d.toDateString());
This will take the first "date only" part of the string that is displayed from the date object.
It could also be done with string manipulation, but this function is actually intended for this usecase, so probably clearer.
Doc for toDateString function
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
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)}
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!