Check if time format is valid in moment.js - javascript

moment.js can format time according to a given format.
Some formats however seem invalid. For instance the website provides the YYYY [escaped] YYYY format. When one however specifies YYYY [escape, the time is formatted like 2014 [121campe its clear that e and s are converted according to the formatting guidelines, but the format is quite invalid.
Is there a way to check if the format provided is valid and for instance if some aspects will be shown in the resulting string (example format.containsHours, note this should also return true if not HH is part of the format string, but for instance LLLL will print the hours implicitly).
I've found nothing in the documentation thus far.

Moment's validation functions are limited to validating whether a given date/time input string is valid according to a given format. It is assumed that the format(s) are known to the developer. It's not intended to accept the format string itself from a variable source such as the end user.
So no, there are no methods for confirming that the format string is valid.

This could work:
function isValidDate(date) {
return (moment(date).toDate().toString() !== "Invalid Date")
}

Use this function
function checkIfDateIsValidUsingMoment(dateString,format)
{
var m=moment(dateString,format);
return m._pf.charsLeftOver ==0 && m._pf.unusedTokens.length==0 && m._pf.unusedInput.length==0 && m.isValid();
}
Above function takes datestring and format, Moment object has isvalid method but its less usable for strict date validation.
Moment Object has _pf which stores info about parsed date.
charsLeftOver: no of chars that do not match (Means extra character, invalid date)
unusedInput: array containing details about unused inputs
unusedTokens: array containing details about unused tokens
For ex :
moment("25 october 2016aaaa","DD MMM YYYY")
This object has "aaaa" as invalid character so it is available in _pf object
You can validate date using these details.

Related

How can I check month and day order in mixed date format?

There's column which contains date in different formats (ie. YYYY-MM-DD or YYYY-DD-MM).
When I query it with format time:date, it throw an error: date/time field value out of range: "2022-23-02"
How can i solve it?
How can I check if it's YYYY-MM-DD or YYYY-DD-MM or another?
If you have no field that tells you whether it's YYYY-DD-MM or YYYY-MM-DD, you are kinda out of luck because it's possible that a value could be valid in both formats.
If you are able to redesign, and you must store the date as a string then use YYYY-MM-DD as it's easier for sorting. Optimally, just pass a JavaScript Date object to field of type date, timestamp, or timestampz to the database driver or orm and let it handle the conversion for you. Here's an example with node-postgres: https://node-postgres.com/features/types (the section labeled "date / timestamp / timestamptz")

Moment.js returns Invalid Date

The following code
const m = moment('08:45').format('HHmm')
returns
'Invalid date'
I have also tried .format('HH:mm')
Any ideas about what is going wrong here?
Just go ahead and pass in a format string as the second argument of the moment() function so that moment knows that you're passing in a time. So change your code to this:
const m = moment('08:45', 'HH:mm').format('HHmm');
and you'll be good to go :)
The input string doesn't match any of the expected date formats, so you need to add a second argument to tell moment how to parse the input.
String:
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.
String + Format:
If you know the format of an input string, you can use that to parse a
moment.
moment("12-25-1995", "MM-DD-YYYY");
const result = moment('08:45', 'HH:mm').format('HHmm');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Timestamp conversion is invalid

I am trying to convert a timestamp, but conversion is giving me 'invalid date' as result.
new Date("2019-01-05T13:99:99.424Z") // invalid date
why this date conversion is invalid?
also, what is the meaning of T13:99:99.424Z and where is this format explained. i have checked in mdn docs, but did not find details of this format.
The date which you entered is invalid because 99 is not valid in terms of mins/secs. Try this :
`new Date("2019-01-05T13:10:10.424Z").`
The T doesn’t really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

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 can I parse this date string consistently across browsers?

I'm using Javascript's Date object to parse a string into a milliseconds timestamp. I'm using Date.parse(), and the strings I'm parsing are of the following format: "2012-07-06 12:59:36-0600"
Date.parse performs nicely in Chrome, parsing into the correct timestamp I'd anticipate. However, every other browser returns "NaN" when I run the string through Date.parse().
I know that the Date object implementation is browser-specific, but I'd like to find a javascript solution that's capable of parsing strings of this type for any browser. Any suggestions on what else I could use in Javascript to achieve this?
Convert the input to valid ISO 8601:
Date.parse("2012-07-06 12:59:36-0600".replace(' ', 'T'));
This was tested (and works) in Firefox.
Note:
Note that while time zone specifiers are used during date string
parsing to properly interpret the argument, they do not affect the
value returned, which is always the number of milliseconds between
January 1, 1970 00:00:00 UTC and the point in time represented by the
argument.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse
Have you tried DateJS? Maybe you don't want to add another library, but it will solve your crossbrowser problem.
If the format is consistent, you can parse it yourself:
var date = "2012-07-06 12:59:36-0600";
function parseDatetime(input) {
var match = input.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})([-+]\d{4})/);
match.shift(); // discard the "full match" index
match[2]--;
match[4] += parseInt(match[6],10);
return new Date(match[0],match[1],match[2],match[3],match[4],match[5]);
}

Categories

Resources