Moment JS Date and time to timestamp in moment.js - javascript

I am getting a text value and it is formatted like this : "9/19/2018 10:00 AM".
How would you go about turning this into an epoch timestamp using moment.js or just javascript?
EXAMPLE:
console.log(moment('4/17/2018 10:00 AM', 'mm/dd/yyyy hh:mm a').format('x'));

Use the date string to create a date Object and then use getTime() method of the Object.
date = new Date("9/19/2018 10:00 AM");
console.log(date.getTime())

normal js
new Date("9/19/2018 10:00 AM");
if you want to do with moment js
moment("9/19/2018 10:00 AM").unix()

The issue in your code is that you are using wrong tokens while parsing your input. Moment token are case sensitive and mm stands for 0..59 minutes, dd stands for day name (according locale) and there is no lowercase yyyy supported.
Use M for 1..12 month number, uppercase D or DD for day of month and uppercase YYYY for year as stated in moment(String, String) docs.
Your code could be like:
console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').format('x'));
console.log(moment('4/17/2018 10:00 AM', 'M/D/YYYY hh:mm a').valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Note that you can use both format('x') (returns a String) and valueOf() (returns a Number).
I suggest to use moment(String, String) over new Date() (Date.parse()) because this way you explicitly state how to parse you input (what would you expect for input like 1/2/2018? 1st of February or January 2nd?). See here a note about Date.parse behaviour
Somewhat surprisingly, these formats (e.g. 7/2/2012 12:34) are also unambiguous. Date.parse favors US (MM/DD/YYYY) over non-US (DD/MM/YYYY) forms.
These formats may be ambiguous to humans, however, so you should prefer YYYY/MM/DD if possible.

Related

Does dayjs support ordinals in month? (Feb. instead of Feb, for germany language)

I am trying to get following representation of a month in German: Feb.
I tried so far:
'Do MMM YYYY'
and
dayjs(date).format('Do MMM YYYY')
With momentjs you used to get 1. Feb. 2012 but with dayjs I get 1. Feb 2012. I tried MMMo but didn't work.
There seems to be no format supporting a conditional '.' for cases such as the german "März". The cleanest workaround I could come up with is the following:
const date = dayjs("2019-03-24").locale("de")
date.format(`MMM${[2, 5, 6].includes(date.$M) ? '' : '.'} YYYY`)
This checks if the provided date is a month with 4 character (März, Juni or Juli) and does not add the '.' in such cases. All other months will be shortened with a '.' at the end, e.g. "Jan.", "Feb." etc..

How to convert localized date string to date object using moment

Using moment how can we convert localized date string to javascript date object?
Followed below steps, but got Current Output(check below).
How can we get Expected Output?
Could you please help me.
Ex: Setting moment locale as 'fr'
moment.defineLocale('fr', [localeObject][1]);
Now we get the date string as "27 févr. 2020 18:23:50"
How can we convert it as dateobject?
moment("27 févr. 2020 18:23:50")
Expected output:
Thu Feb 27 2020 18:23:50 GMT+0530 (India Standard Time)
Current Output:
Invalid Date
You are getting Invalid Date because "27 févr. 2020 18:23:50" is not in ISO 8601 nor in RFC 2822 compliant form, so you have to use moment(String, String). Moreover you have to use french locale, see i18n section of the doc.
As described in the docs, you can use DD for days of the month, MMM for month name (locale aware), YYYY for 4 digit year, HH for 0-23 hours (lowercase hh for 1-12 hours), mm for minutes and ss for seconds.
Then you can use toDate() to get a JavaScript date from a moment object:
To get a copy of the native Date object that Moment.js wraps, use moment#toDate.
Snippet with working code sample:
console.log( moment("27 févr. 2020 18:23:50", "DD MMM YYYY HH:mm:ss").toDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/fr.js"></script>

Date conversion issue in JS

I have a date in local time zone which is Mon Jan 13 2020 00:00:00 GMT+0530 (India Standard Time).
I need this
Jan 13 2020
date in UTC. when i converted using
moment(
moment(start_date).format('mm-dd-yyyy'),
).Unix();
i am receiving a UNIX time stamp corresponding to the date Jan 12 2020 in UTC.
what i need is for Jan 13 2020 get a UTC timestamp of date Jan 13 2020 instead of getting Jan 12 2020. Time values are not important.
Get the UTC timestamp like this:
moment.utc('Jan 13 2020').format('X')
Above will give you the UTC timestamp in seconds.
If you want milliseconds, use x instead of X.
Breaking down your statement:
moment(start_date)
does not provide the parse format to moment.js so you will get a warning to that effect. In this case, moment.js will fallback to the built–in parser as if you'd written:
moment(Date.parse(start_date))
so you are hoping the built–in parser parses it correctly.
Then there is:
.format('mm-dd-yyyy')
which will return a date string in that format or Invalid Date if the parser couldn't parse the string.
However, likely you have used the wrong tokens so the result will be something like "30-mo-yyyy":
mm is two digit minute, if you want two digit month then use MM
dd is two letter day name, if you want two digit day in month use DD
yyyy is not a valid token, if you want the four digit year then use YYYY
So the format tokens should be:
.format('MM-DD-YYYY')
The result is then passed to moment, again without specifying the input format so again moment will show a warning and use the built–in parser again with the same potential for errors or invalid Dates. If parsed correctly, it will return a Date for the local timezone for the Date.
.Unix()
Is not a valid moment method, likely you want .unix(), which produces a UNIX timestamp (time value) for the equivalent UTC time. If the host system is set to +5:30 then the UTC time will be 5:30 earlier (and if it's before 5:30 am local, the date will be the day before).
If you want to parse the string correctly and get a date for the start of the day, then do:
moment(start_date, 'ddd MMM DD YYYY HH:mm:ss ZZ').startOf('day').unix()
Or create a formatted string however you like. A much more common format is YYYY-MM-DD, so consider:
let start_date = 'Mon Jan 13 2020 00:00:00 GMT+0530 (India Standard Time)';
// Get UNIX timestamp for start of day
console.log(
moment(start_date, 'ddd MMM DD YYYY HH:mm:ss ZZ').startOf('day').unix()
);
// Get formatted date string
console.log(
moment(start_date, 'ddd MMM DD YYYY HH:mm:ss ZZ').format('YYYY-MM-DD')
);
console.log(
moment(start_date, 'ddd MMM DD YYYY HH:mm:ss ZZ').format('DD MMM YYYY')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

Invalid date in IE11 even though date format is ISO 8601 supported

I have used moment to convert date to ISO supported format as it's working fine on chrome & firefox but not on IE11 so
I as per the docs YYYY-MM-DD is supported iso format,
here my js_time1 format is as mentioned ddd MMM D YYYY hh:mm:ss
so i have used this to fomrat it
var js_time = moment(js_time1).format('YYYY-MM-DD');
i have also tried
var js_time = moment(js_time1,'ddd MMM D YYYY hh:mm:ss').format('YYYY-MM-DD');
but no use.
Format for js_time1 is Mon Aug 3rd 2018 12:12:21
Thanks in advance
Assuming js_time1 is what you've shown as "format for" ("Mon Aug 3rd 2018 12:12:21"), there are three problems:
August 3rd, 2018 was a Friday, not a Monday.
Your parsing format uses D for 3rd. D doesn't match ordinals, that's Do.
You're using hh (1-12) for hours, which is meant to be used with a. I assume your time is in 24-hour format, so that's HH.
It works if you fix those things (including fixing the error in the string):
var js_time1 = "Fri Aug 3rd 2018 12:12:21";
var js_time = moment(js_time1,'ddd MMM Do YYYY HH:mm:ss').format('YYYY-MM-DD');
console.log(js_time);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Parse Date "01/01/2016 Fri"

I am trying to parse a date in JavaScript, but the particular format is giving me fits. I have exported data from my credit card company and the format of the date field is not compatible with Date.parse or moment().isValid().
E.g.
Date.parse("01/01/2016 Fri") // NaN
moment("01/01/2016 Fri") // false
I'm not sure if I should do something with a RegEx .test() or .matches() because this is being used for a CSV import utility where dates may be in different formats. I was surprised the utility functions above didn't work.
Look in the Moment docs to see how to parse a date in any format. The first argument is the date string, the second is the format string. Alphanumeric characters are ignored, so you don't need to worry about slashes vs. dashes.
moment("01/01/2016 Fri", "MM-DD-YYYY ddd)
Check out the Mozilla MDN on Date.parse():
The parse() method takes a date string (such as "Dec 25, 1995") and
returns the number of milliseconds since January 1, 1970, 00:00:00
UTC. This function is useful for setting date values based on string
values, for example in conjunction with the setTime() method and the
Date object.
Given a string representing a time, parse() returns the time value. It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT". It understands the continental US
time zone abbreviations, but for general use, use a time zone offset,
for example, "Mon, 25 Dec 1995 13:30:00 +0430" (4 hours, 30 minutes
east of the Greenwich meridian).
From this, it looks like your problem is that you're giving the date in the improper format:
It
accepts the RFC2822 / IETF date syntax (RFC2822 Section 3.3), e.g.
"Mon, 25 Dec 1995 13:30:00 GMT".
Check this out:
Invalid values in date strings not recognized as ISO format as defined by ECMA-262 may or may not result in NaN, depending on the browser and values provided, e.g.:
// Non-ISO string with invalid date values
new Date('23/25/2014');
TL;DR - you're passing the values in a format that is not recognized, which is why it's returning NaN.
Try this source for Regexes for dates: Regexlib.com. The site is a little out of date, but the info is great. It has tons of different Regexes for different date formats.

Categories