Always getting wrong time difference using Moment - node.js

I have end date time in UTC format and with that time I am doing comparing it with current time on my server. I want to check that time difference should be 5 minutes. But I am always getting huge time difference.
console.log('utc format... ', currentDate, slot.endTimeWithDuration);
// log -> utc format... moment("2019-11-30T10:16:00.002") 2019-11-30T16:40:00Z
console.log('diff.... ', moment(slot.endTimeWithDuration).diff(currentDate,'minutes'))
// diff.... 383
How can I resolve this?

Try this something like :
moment.utc(moment(endTime, "HH:mm:ss").diff(moment(startTime, "HH:mm:ss"))).format("mm")
Or You can also make it more simple like below example:
var startTime = moment("07:27:28 am", 'hh:mm:ss a');
var endTime = moment("08:24:59 pm", 'hh:mm:ss a');
endTime.diff(startTime, 'hours');

Related

How to format the date and time into UTC format?

I'm working in nodejs.
I have the input has date and time "1/6/2022, 2:49:22 AM".
need to convert the date and time to UTC format "2022-01-05T13:04:22.137Z".
please help me with the solution.
code:
let date =new Date().toLocaleString("en-US", { timeZone: "Pacific/Chatham" });
console.log(date);
how to convert this date and time "1/6/2022, 2:49:22 AM" into UTC format "2022-01-05T13:04:22.137Z".
kindly help me with the solution.
In javascript
var isoDateString = new Date().toISOString();
console.log(isoDateString);
The toUTCString() method returns a date object as a string, according to UTC.
Tip: The Universal Coordinated Time (UTC) is the time set by the World Time Standard.
Note: UTC time is the same as GMT time.
Source

Parsing a 'llll' locale aware formatted data to Postgres default date format using MomentJS

I'm successfully fetching some data using Axios and I need to store this data to my Postgres database.
One of the fields from the fetched data is a pubDate field, which is formatted exactly like this:
"Tue, 15 Apr 2020 20:01:30 +0000"
Reading through Moment docs, this seems to be this "locale aware 'llll'" format.
So, what I need is to parse this pubDate and format it as the default Postgres date format. The pubDate would then look something like this:
"2020-04-14T20:01:30"
I've been searching for this process for quite some time and just wasn't able to find anything that would work.
I've tried this (did not work), based on the String + Format from docs:
let date = moment(pubDate, 'llll').format();
I'm new to NodeJS, sorry if I messed up something. Thank you in advance!
Looks like MomentJS doesn't have a default function for this (I couldn't find anywhere), so I've created one:
function parseDate (date) {
// date format: "Thu, 16 Apr 2020 18:29:49 +0000"
date = String(date);
// date format (after , split): ["", "Day", "Abbreviated Month", "Year", "hour:minute:seconds", "+0000"]. I.E.: ["", "16", "Apr", "2020", "18:29:49", "+0000"]
let dateInfo = String(date).split(",")[1].split(" ").slice(1, -1);
// ["Day", "Abbreviated Month", "Year", "hour:minute:seconds"]
let dateString = dateInfo[2] + '-' + moment().month(dateInfo[1]).format("M") + '-' + dateInfo[0] + ' ' + dateInfo[3];
const parsedDate = moment(dateString, 'YYYY-MM-DD hh:mm:ss');
return parsedDate;
}

Moment.js sets dates to 1 day behind

I am using 2.22.1 to format dates.
When i put in a date that comes from a date selector, moment will put the date back one day. For example, when I try to format a date in the following way:
Example 1:
const day = new Date(value).getDate();
const month = new Date(value).getMonth();
const fullYear = new Date(value).getFullYear();
console.log('day', day); // 7
console.log('month', month); // 5
console.log('fullYear', fullYear); //2018
Formatting function:
moment.utc(new Date(month + ' ' + day + ' ' + fullYear), 'MM-DD-YYYY').format('DD-MM-YY')
Output: 06-05-18
Expected: 07-05-18
Example 2:
Input: Thu May 31 2018 00:00:00 GMT+0100 (GMT Summer Time)
Formatting function:
moment.utc(new Date(value)).format('DD-MM-YY')
Output: 30-05-18
Expected: 31-05-18
moment.utc will convert the input to universal time.
You are running new Date(...) with an input that's based on GMT +1.
If you think about this, it makes total sense.
Your output is 30-05-18, because it's 11 PM / 23:00 o'clock on the previous day.
This (how ever) would in fact work:
moment('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
// alternatively (and preferrably) this:
moment.utc('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
and output: "06-05-18"
Because the non utc version does not take a time input in this example.
One of the reasons moment.js exists, is to get rid of Date in your code all together.
(Keep in mind tho, that Date has drastically improved now. DateTimeFormat is a game changer)
Please just read the momentjs documentation on how to properly use moment.
edit:
If you want to process 400000 dates with this, I'd advise using RegExp, .split, .exec, .slice or Date instead.
(I can relate since I wrote a client sided Log parser with javascript generators and Service Workers for a statistical anti-cheat analysis)
I truly recommend playing around with such things to raise your knowledge.
I just ran into this issue and a quick fix I found for the time being processed in "Zulu time" (due to the Z at the end of the string) is to add .LocaleString() after the date variable.
I find that for data consistency, it's easier to store data in UTC time and then convert it to the locale string when displaying the data to the user.
For example, I'm using:
moment.utc(dateVariable.toLocaleString()).format("MM/DD/YYYY")

Parsing dates in node.js: moment.utc() is not returning the correct UTC unix time

I'm trying to parse a date string and return the corresponding unix time to midnight at the start of the date in the UTC zone. However, my node.js keeps returning the unixtime at the start of that date in MY timezone.
What am I doing wrong? This should print 1440633600 to the console but it prints a number corresponding to the unix time in my timezone, not UTC.
var moment = require('moment');
var datestring = "August 27 2015";
var unixDate = new Date(datestring);
var myDate = moment.utc(unixDate);
console.log(myDate.format('X'));
"datestring" will not always contain a "Z" at the end (which indicates UTC) but it might sometimes, so I can't just add a "Z" before parsing. There's got to be something I'm missing here...
TL;DR:
var myDate = moment.utc(datestring, 'MMMM DD YYYY');
The explanation:
var unixDate = new Date(datestring); with datestring set to "August 27 2015" will set unixDate to the timestamp corresponding to midnight on August 27 2015 in your time zone.
Subsequently, var myDate = moment.utc(unixDate) sets myDate to a moment object set to that same time. Since you are sending it a timestamp and not a date, it has no reason to adjust for timezone. Since you generated the timestamp based on the time in your timezone, that's what moment sees.
One fix is to change that line to var myDate = moment.utc(datestring, 'MMMM DD YYYY');. Since moment will be getting a string to process rather than a UNIX timestamp, it will select midnight on August 27 2015 in UTC.

How to convert local time stored as UTC to actual correct UTC value

I have local time stored in mongodb e.g. "2016-04-25T09:30:00.000Z"
It's saved as 'UTC' (Z at the end) but in fact it's literal representation of local time. I have also timezone stored, e.g. "Europe/London" so i have all the info i need to convert to correct utc time.
In that cause result should be "2016-04-25T08:30:00.000Z" but i can't find the way how to do it. I tried moment-timezone.
There is a much easier and less error prone way than what you have there. Simply parse the date with a format that ignores the Z at the end:
moment.tz("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS', 'Europe/London').format()
"2016-04-25T09:30:00+01:00"
The date having been parsed correctly, getting the UTC date is as simple as calling .toISOString()
moment.tz("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS', 'Europe/London').toISOString()
"2016-04-25T08:30:00.000Z"
Note that if that is a local date, regardless of timezone, you can omit the timezone identifier and just use the browser's local time:
moment("2016-04-25T09:30:00.000Z", 'YYYY-MM-DDTHH:mm:ss:SSS').format()
"2016-04-25T09:30:00-05:00"
But I think that you're using Node so that second one probably isn't what you want.
I do believe that problem is the format which specifies 000Z zone for moment lib. It says that it's already UTC 0 and timezone = 'Europe/London' is ignored in such case.
moment.utc(moment(start).tz(timezone)).format()
is working correctly with date format"2016-04-25T09:30:00".
Check out runnable version here
Found it!
var start = "2016-04-25T09:30:00.000Z";
var timezone = 'Europe/London';
var mZoned = moment.tz(start, timezone);
var mStart = moment.utc(start);
var correctedStart = moment.utc(1000*(mStart.unix() - (mZoned.utcOffset()*60)));

Resources