How to get difference between two datetime of moment.js? - javascript

How can I calculate the difference between two dates time in moment.js?
moment.duration((moment(startDate).format("MM-DD-YYYY h:mm:ss a")).diff(moment(new Date()).format("MM-DD-YYYY h:mm:ss a")));
and My startDate = 2022-02-02T12:12:25Z

I found the solution ,may help other people :
var now = moment(new Date(), "DD/MM/YYYY HH:mm:ss");
var then = moment(new Date(startDate), "DD/MM/YYYY HH:mm:ss");
var diffTime = moment.duration(then.diff(now));
and it depends to you how you want to get difference in seconds ,minutes or hours :
diffTime.asHours();

Related

Check If date exceeds 24Hrs from start date in moment

Check If date exceeds 24Hrs from start date in moment.
Ex:
My date string **"27-05-2021 10:26:29 PM"**. I want to check from this start date exceeds or not. I'm using moment.js
You can use moment js format and diff function.
let a = moment("27-05-2021 10:26:29 PM", "DD-MM-YYYY hh:mm:ss A");
let b = moment();//todays date in local time zone
console.log(a.diff(b, "hours"));
First of all you need to parse string to get a valid date.
If you will use moment(dateString) directly, invalid date will be the result:
const dateString = '27-05-2021 10:26:29 PM';
const startDate = moment(dateString); // invalid date
so:
// parse string using format string to get a valid date
const dateString = '27-05-2021 10:26:29 PM';
const startDate = moment(dateString, 'DD-MM-YYYY hh:mm:ss a');
// finally get the difference from other date in hours/minutes/years
const today = moment(); //to get todays date
const hoursDiff = today.diff(startDate, 'hours'); //diff in hours
const minutesDiff = today.diff(startDate, 'minutes'); //diff in minutes
You can use diff and duration
var x = moment('27-05-2021 10:26:29 PM', ['DD-MM-YYYY HH:NN:SS']);
var y = new moment()
var duration = moment.duration(x.diff(y)).as('hours');
console.log(duration);

How to change the timezone with moment.js without changing the time?

I have a datepicker which returns local time in the format dddd, MMMM DO YYYY, h:mm:ss a to a variable localTime. I have an option to change the timezone from a <select> which contains timezone names from moment.tz.names(). When timezone changes, I need to change the timezone of localTime to new timezone without changing the time.How can I do this with moment.js
let timeString = "Wednesday, January 10th 2018, 9:10:19 pm";
let localTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').format('YYYY-MM-DD HH:mm:ss ZZ');
let localTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').utc().format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimezone = "EST";
let newTime = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).format('YYYY-MM-DD HH:mm:ss ZZ');
let newTimeInUtc = moment(timeString, 'dddd, MMMM DO YYYY, h:mm:ss a').tz(newTimezone).utc().format('YYYY-MM-DD HH:mm:ss ZZ');
console.log(localTime);
console.log(localTimeInUtc);
console.log(newTime);
console.log(newTimeInUtc);
Here time in UTC is same for localTime and newTime
According to Docs
Maybe you are looking for format2 in the following code.
format1 - creates moment and sets the time-zone (will not update the offset).
format2 - creates the moment with the given timezone.
var date = moment().format("dddd, MMMM D YYYY, h:mm:ss a"), format = "dddd, MMMM D YYYY, h:mm:ss a", timezone = "America/New_York";
var format1 = moment(date,format).tz(timezone);
var format2 = moment.tz(date, format,timezone);
console.log(format1.format(format)+" -> "+format1.format());
console.log(format2.format(format)+" -> "+format2.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.14/moment-timezone-with-data.min.js"></script>
See this Github issue once.

get UTC timestamp from formated date - javascript

I have a UTC date string -> 10/30/2014 10:37:54 AM
How do I get the timestamp for this UTC date? As far as I know, following is handling this as my local time
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime();
Thank you
You can use Date.UTC to create a UTC format date object.
Reference:
Stackoverflow
MDN
(function() {
var d = new Date();
var d1 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds()));
console.log(+d);
console.log(+d1);
})()
You can decrease the "TimezoneOffset"
var d = new Date("10/30/2014 10:37:54 AM");
return d.getTime() - (d.getTimezoneOffset() *1000 * 60);
Also u can use the UTC function
var d = new Date("10/30/2014 10:37:54 AM");
return Date.UTC(d.getFullYear(),d.getMonth()+1,d.getDate(),d.getHours(),d.getMinutes(),d.getSeconds());
If the format is fixed, you could easly parse it and use the Date.UTC() API.
A quick hack would be to append UTC to the end of your string before parsing:
var d = new Date("10/30/2014 10:37:54 AM UTC");
But I would advise you to use a library like moment.js, it makes parsing dates much easier
Try Date.parse
var d = new Date("10/30/2014 10:37:54 AM");
var timstamp = Date.parse(d) / 1000;
Hope this helps:
Date date= new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat sdf2 = new SimpleDateFormat("HH:mm:ss");
date = sdf.parse(date.toString());
String timestamp = sdf2.format(date);

JavaScript - DD/MM/YYYY HH:SS to milliseconds

I have the following code:
23/09/2014 - 09:15 (DD/MM/YYYY - HH:SS)
I need to use JS to reformat in milliseconds.
var dateString = "23/09/2014 - 09:15",
dateArgs = dateString.match(/\d{2,4}/g),
year = dateArgs[2],
month = parseInt(dateArgs[1]) - 1,
day = dateArgs[0],
hour = dateArgs[3],
minutes = dateArgs[4];
var milliseconds = new Date(year, month, day, hour, minutes).getTime();
you can use Moment.js See http://jsfiddle.net/mendesjuan/jpkkngjw/
// getTime() returns milliseconds since epoch
moment("23/09/2014 - 09:15", "DD/MM/YYYY - HH:SS").toDate().getTime()
Here are some other examples of using Momento
moment().format(); // "2014-09-08T08:02:17-05:00" (ISO 8601)
moment().format("dddd, MMMM Do YYYY, h:mm:ss a"); // "Sunday, February 14th 2010, 3:25:50 pm"
moment().format("ddd, hA"); // "Sun, 3PM"
moment('gibberish').format('YYYY MM DD'); // "Invalid date"

How to get three month ago date in javascript in the format as YYYYDDMM efficiently

I know a way to do in java:
Calendar c5 = Calendar.getInstance();
c5.add(Calendar.MONTH, -6);
c5.getTime(); //It will give YYYYMMDD format three months ago.
Is there a way to do this in javascript. I know that I can use
Date d = new Date(); parse it and do some code to get the format.
But now I dont want to do parsing and getting three month ago date.
var dt = new Date('13 June 2013');
dt.setMonth(dt.getMonth()-1)
Then you can use this piece of code from this answer to convert it to YYYYMMDD
Date.prototype.yyyymmdd = function() {
var yyyy = this.getFullYear().toString();
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
return yyyy + (mm[1]?mm:"0"+mm[0]) + (dd[1]?dd:"0"+dd[0]); // padding
};
d = new Date();
d.yyyymmdd();
Something to be careful of. If you're at Mar 31 and subtract a month, what happens? You can't get Feb 31! See this answer for more details.

Categories