How to create a javascript date from 12 hour format - javascript

How can I create a Date object from a date with this format:
03/23/2016 02:00:00 PM

The Date object can parse strings: new Date('03/23/2016 02:00:00 PM')
For example:
var date = new Date('03/23/2016 02:00:00 PM') // => "Wed Mar 23 2016 14:00:00 GMT-0700 (PDT)"
date.getFullYear() // => 2016
However, I would recommend using a library that someone else has already spent time considering the edge cases, like time zones, etc. (a good one I've used is moment.js).
Keep in mind (from the moment.js docs):
Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

var date = new Date("3/23/2016 02:00:00 PM");
console.log(date);
You can then access all the methods of the Date object.

Looking at MDN
var date = new Date('03/23/2016 02:00:00 PM')

You can use something like date.js:
First use script, then write date:
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
....
document.write(new Date().toString("dd:MM:yyyy hh:mm:ss tt"));

Related

Javascript Date constructor depending by timezone [duplicate]

This is what I get in chrome console. I pass "2016-09-05"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date.
Another constructor shows the right date
Passing it comma separated needs some tokenizing + parsing + making month zero indexed which I want to avoid
If you omit the time in the new Date(string) constructor, UTC time is assumed. So the displayed value is actually correct. Use new Date('2016-09-05T00:00') to create the date object in local time.
Edit: while some browsers seem to support the yyyy-MM-dd HH:mm format, it's not officially supported, and, as mentioned in the comments, this doesn't work in Safari. I've updated the answer to use a T instead of a space between date and time.
Per the ECMAScript® 2023 Language Specification:
Date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above
date-only forms immediately followed by one of the following time
forms with an optional UTC offset representation appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
You could use the Solution from UTC Date Conversion.
Which basicall does the following:
console.log(new Date("2014-12-23"));
console.log(convertDateToUTC(new Date("2014-12-23")));
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
The output would be like that in the console (for me at least :D)
Tue Dec 23 2014 01:00:00 GMT+0100 (Mitteleuropäische Zeit)
Tue Dec 23 2014 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
use setFullYear the syntax is Date.setFullYear(year,month,day)
mydate = new Date();
mydate.setFullYear(2016, 08, 05);

What format do I use with moment to give me same string as `new Date()`?

I'm using moment() and want to know if there's a shortcut to give me the same date string as new Date() would give me.
I have to do some timezone conversions so using moment.js makes that easier, but I need the same date format: Thu Oct 06 2016 23:08:53 GMT-0700 (PDT) as the native Date object would give me.
I would assume there is a shortcut for this, but I can't find it.
moment.tz('America/New_York').format('???')
I could not find a shortcut however this gives the string I need:
moment.tz('America/New_York').format('ddd MMM DD YYYY HH:mm:ss [GMT]ZZ (z)')
from the docs: http://momentjs.com/docs/#/displaying/
Returns: Fri Oct 07 2016 02:25:17 GMT-0400 (EDT)
if you have no idea which timezone the browser is currently in, you can try moment.tz.guess(), it isn't 100% correct for timezone offset that has multiple names though:
var d = moment()._d;
d.toString().replace(/\([\w ]+\)$/, moment.tz(d, moment.tz.guess()).format('(z)'));
The date format you're referring to, depends on the culture/language of your browser. That aside, if you want the same format as the standard new Date().toString() returns, you just use the toString() method on the moment object, without any arguments:
moment().toString();
Source: http://momentjs.com/docs/#/displaying/as-string/

Incorrect date shown in new Date() in JavaScript

This is what I get in chrome console. I pass "2016-09-05"(YYYY-MM-DD) as the date and it shows me Sept 4,2016 as the date.
Another constructor shows the right date
Passing it comma separated needs some tokenizing + parsing + making month zero indexed which I want to avoid
If you omit the time in the new Date(string) constructor, UTC time is assumed. So the displayed value is actually correct. Use new Date('2016-09-05T00:00') to create the date object in local time.
Edit: while some browsers seem to support the yyyy-MM-dd HH:mm format, it's not officially supported, and, as mentioned in the comments, this doesn't work in Safari. I've updated the answer to use a T instead of a space between date and time.
Per the ECMAScript® 2023 Language Specification:
Date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes “date-time” forms that consist of one of the above
date-only forms immediately followed by one of the following time
forms with an optional UTC offset representation appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
You could use the Solution from UTC Date Conversion.
Which basicall does the following:
console.log(new Date("2014-12-23"));
console.log(convertDateToUTC(new Date("2014-12-23")));
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
The output would be like that in the console (for me at least :D)
Tue Dec 23 2014 01:00:00 GMT+0100 (Mitteleuropäische Zeit)
Tue Dec 23 2014 00:00:00 GMT+0100 (Mitteleuropäische Zeit)
use setFullYear the syntax is Date.setFullYear(year,month,day)
mydate = new Date();
mydate.setFullYear(2016, 08, 05);

Why does moment.js return this date wrong?

I'm simply trying to take an input string and convert it to a date object.
moment.utc('2000-01-01T00:00:00.000Z').toDate()
But it returns this...
Fri Dec 31 1999 19:00:00 GMT-0500 (EST)
Thanks
That is a valid JavaScript Date Object. You can test this by opening a console in Chrome or Firefox, then entering the following:
// Mon Nov 24 2014 09:54:00 GMT-0800 (PST) (looks the same as your example)
console.log( new Date() );
If you want to format the value coming out of moment.js, you can use its format method and a mask.
// Example: November 24th 2014, 09:58:12am
var fdate = moment().format('MMMM Do YYYY, h:mm:ss a');
Moment.js doesn't modify the prototype, it simply wraps it.
If you want to convert a string to a date object using moment.js, you can just call it as such:
moment(your_date); // Unless in UTC mode this will display as local time
In your instance you're using the UTC mode.
2000-01-01T00:00:00.000Z is the GMT date/time.
Using moment.utc("2000-01-01T00:00:00.000Z").toDate() returns this date/time according to your timzone settings.
See : http://www.digitoffee.com/programming/get-local-time-utc-using-moment-js/94/
Hope it helps.

Date is invalid in IE and Firefox but is chrome it works fine

var stdate=document.forms["myForm"]["from"].value;
var endate=document.forms["myForm"]["to"].value;
var fromDate = new Date(stdate);
var toDate = new Date(endate);
alert(fromDate);
Input:
from: 19-Mar-2014 03:13:50 PM
Output: (in IE & Firefox)
invalid Date
in Chrome broswer:
Wed Mar 19 2014 15:13:50 GMT-0400 (Eastern Daylight Time)
What date format should I use so that all browsers support? Or how should I handle it?
In most cases, new Date(datestring) is all you need. But you need to chose the format carefully.
Here's a nice compatibility table: http://dygraphs.com/date-formats.html
The short version is this:
Dates only? use YYYY/mm/DD; never use hyphens in this format
Need time, but local time is OK? use YYYY/mm/DD HH:MM:SS; again, no hyphens
OK to ignore IE<9? Consider using ISO8601 with whole seconds (YYYY-mm-DDTHH:MM:SSZ, or with time-zone)
Need a UTC time in IE8? You'll have to do something clever. Xotic's answer looks good here.
As documented on MSDN (IE) - the Date constructor supports either a timestamp or a Datestring in a Format supported by Date.parse. According to the docs this is either RFC2822 or ISO 8601. some examples: 2011-10-10 or Mon, 25 Dec 1995 13:30:00 GMT should be valid arguments.
I would use an ISO8601
formatted string in UTC as my input, but then manually
split
this string into parts and feed them into my
Date
constructor thus avoiding date parsing issues.
Example
var iso8601 = '2014-03-19T03:13:50.000Z',
parts = iso8601.slice(0, -1).split(/[\-T:]/),
dateObject;
parts[1] -= 1;
dateObject = new Date(Date.UTC.apply(undefined, parts));
console.log(dateObject.toUTCString());
Output
Wed, 19 Mar 2014 03:13:50 GMT
On jsFiddle

Categories