What format of date/time object does moment js accept? - javascript

moment("2019-08-22T09:00:00") successfully creates a Moment object, but if I try to do moment("9:00") it doesn't. If I've provided only the hour like that, I have to do moment("9:00", "h:mm").
My Question Is:
What format(s) of date/time string do I have to pass to moment() in order to not have to specify the format, as I did with moment("9:00", "h:mm")?

From documentation:
When creating a moment from a string, we first check if the string
matches known ISO 8601 formats, we then check if the string matches
the RFC 2822 Date time format before dropping to the fall back of new
Date(string) if a known format is not found.

You can see on the moment's document, there are three categories of tokens can be used in the format:
Week year, week, and weekday tokens
Locale aware formats
Hour, minute, second, millisecond, and offset tokens

You need to pass a second argument to moment() using a .format() method
Try this:
moment("2019-08-22T09:00:00").format('MM/DD/YYYY');

Related

Difference in new Date() output in Javascript

I tried with two methods to generate Date first by passing whole date string and second with year, month, day combination. But I am getting different outputs while the same date is being provided. The Day is not right. It should be 30 June in the first too.
const oldDate = new Date('2020-06-30');
const newDate = new Date('2020', '05', '30');
console.log(oldDate.toString(), newDate.toString());
When you instantiate a Date by passing a string, it's supposed to be a full ISO 8601 string which specifies the time zone. As you dont specify it, it takes GMT+0, and you seem to be located at GMT-7. You should write this instead:
console.log(new Date('2020-06-30T00:00:00-07:00').toString());
The Date constructor that accepts multiple arguments expects them to be numbers, and accepts the month number as a 0-based value (0 = January). The values are expected to be in local time.
The Date constructor accepting a single string argument parses the string according to the specified rules (which apply to your example) and, possibly, unspecified fallback rules the JavaScript engine implementer chose to add (in your case, though, the fallback isn't necessary). When there's no timezone indicator on the string, Date-only forms such as yours are parsed in UTC (date/time forms are parsed in local time).
(The Date constructor accepting a single number expects that number to be milliseconds-since-The-Epoch [Jan 1st, 1970 at midnight, UTC].)
Below format is considered as GMT time and it tries to convert to your local timezone. That's why you notice 7 hours subtracted.
new Date('2020-06-30')
whereas,
Below format is considered as local timezone and no further conversion happen.
new Date('2020', '05', '30');
According to MDN docs:
dateString
A string value representing a date, specified in a format recognized by the Date.parse() method. (These formats are IETF-compliant RFC 2822 timestamps, and also strings in a version of ISO8601.)
Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.
Support for RFC 2822 format strings is by convention only.
Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.
Therefore, when you create date via new Date("2020-06-30") it creates date object in 0 timezone and adjusts time to show it equal to your time zone.

Javascript getFullYear() returns the wrong year [duplicate]

This question already has answers here:
JavaScript's getDate returns wrong date
(12 answers)
Closed 6 years ago.
This is so basic, but it makes no sense to me:
new Date("2010-01-01").getFullYear();
result: 2009
wth? My goal is to reformat the date as mm/dd/yyyy given the format yyyy-mm-dd..
Adding on:
new Date("2010-01-01").getMonth();
result: 11
new Date("2010-01-01").getDate();
result: 31
The date string you're passing into new Date() has no timezone in it. It's being interpreted as UTC. The critical thing to understand here is that a Date is stored as a Unix timestamp (seconds since 1970-01-01 00:00, making 'Date' a misleading name) so if you don't specify the time within the date, it's going to apply a default.
Date.prototype.getFullYear() retrieves the full year for that timestamp in your LOCAL time. (See the docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getFullYear)
You're somewhere west of UTC, and 2010-01-01 UTC is 2009-12-31 in your local time.
And for your final mystery....getMonth() is 0-based, not 1-based, so '11' is December.
Don't use the Date constructor to parse strings, it's largely implementation dependent and inconsistent.
An ISO 8601 date and time without a timezone like "2016-02-29T12:00:00" should be treated as local (i.e. use the host system timezone offset to create a Date), but a date–only string is treated like "2016-02-29" as UTC. The first behaviour is consistent with ISO 8601, but the second isn't.
Some versions of browsers will treat date–only strings as UTC, and some as invalid dates, so always parse strings manually (a two line function or library can help). That way you know how it will be parsed in all hosts.
Provide Time with date in the new Date() as parameter . Then u will get exact Result.

JavaScript Date constructor and UTC

If I use new Date('2015-01-01'), will that give me a point in time equivalent to 2015-01-01T00:00:00Z?
From documentation:
constructors: ... dateString String value representing a date. The
string should be in a format recognized by the Date.parse() method
(IETF-compliant RFC 2822 timestamps and also a version of ISO8601).
From documentation on Date.parse():
If a time zone is not specified and the string is in an ISO format
recognized by ES5, UTC is assumed
However, depending on this behaviour could be risky, as, from the same document:
note that ECMAScript ed 6 draft specifies that date time strings without a time zone are to be treated as local, not UTC

Moment failing on some dates

Here are my dates, to me there is no different whatsoever. Yet moment can't handle them all:
console.info(details.date);
console.info(moment(details.date).format());
console.info('________________________________________');
result.date = moment(details.date, "DD-MM-YYYY H:m").format();
//Console
________________________________________
16/10/10 15:00
Invalid date
________________________________________
09/10/10 15:00
2010-09-10T15:00:00+01:00
How can I make my dates safe.
It appears Moment is using the American Date convention, despite it not being documented in there moment(string) interface.
A simple example is here
According to the documentation for moment(string), if a format is not provided when parsing a string it will first try to match one of the ISO 8601 formats specified in ECMA-262. Failing that, it will simply pass the string to new Date(string), which is the same as using Date.parse.
So the result is entirely implementation dependent. However, most browsers will treat nn/nn/nn as a US style date with two digit year, i.e. mm/dd/yy. But that is not guaranteed and may change from browser to browser.
The fix is to always pass the format when parsing strings.
In the second example, the format specified doesn't match the string supplied. It seems it falls back to Date.parse in this case also.
Your date format string uses hyphons ("-") and actual date uses slashes ("/"), so Moment.Js is unable to parse it. Works fine in following example
$("body").text(moment("16/10/10 15:00", "DD/MM/YY H:m").format())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.js"></script>

How to convert time and date string to ISO format

I have two inputs, a time and a date input. I'm trying to format them as an ISO string to send to the backend using moment.js.
This is what I have so far 01:00 2016-01-01, I need to format or convert that to ISO. Is there a way to do it using Moment?
To convert ISO I recommend the more standard
date.format();
or
JSON.stringify(yourDate)
or if you prefer momentjs:
var date = moment();
date.toISOString();
or
moment(yourDate).format('MM/DD/YYYY'); // <- your custom format string
To know what are the momentjs formatting rules start reading here
Assuming you are referring to ISO8601 and momentjs (2.10.6), I currently do it like this
var example = momentObject.format("YYYY-MM-DD[T]HH:mm:ss");
You need to use moment's parse function to first create the correct moment object from the data that you have (assuming a 24-hour clock, and month listed before the days):
var myMoment = moment("01:00 2016-01-01", "HH:mm YYYY-MM-DD");
Then you can use moment's format function to output the date in the ISO format that you want. Note that calling the format function without any parameters will output ISO 8601 by default:
myMoment.format();
See the moment docs for more info here.
Hope this helps!

Categories

Resources