I am trying to calculate the time difference between two dates using moment-timezones but every time it it showing the same difference.
I am calculating the time like this:
const end_time = moment.tz(end_date, timezone);
const current_time = moment.tz(moment.tz.guess());
const difference = end_time - current_time;
let duration = moment.duration(difference, 'milliseconds');
I am getting the same duration no matter what timezone I set.
Can anybody suggest me how to get the correct difference using moment?
Use diff method, to check the duration differences between two objects
var now = moment.tz("2020-05-14 00:00:00", "Europe/Berlin");
var end = moment.tz("2016-05-14 00:00:00", "Europe/Berlin");
var diff = now.diff(end);
console.log("diff is: " + diff);
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Related
Given a number 1500 which is supposed to represent the time 15:00 (3pm). I'd like to convert it to a moment time and be able to compare it to the current time.
How to make this conversion and how to get the current time in that same format to be able to compare it?
const now = moment();
const time = moment('1500', 'hhmm');
const diff = moment.duration(now.diff(time));
Then to compare you can use
diff.minutes(), diff.seconds(), or diff.hours()
https://momentjs.com/docs/#/displaying/difference/
You can get the current date: moment();
Then you can set the hours and minutes: moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
Altogether that'd be:
const numberString = "1500";
const now = moment();
const nowAtNumberStringTime = moment().set("hour", numberString.substring(0, 2)).set("minute", numberString.substring(2, 4));
const difference = now.diff(nowAtNumberStringTime);
console.log(difference);
There is a start date for the process in string form:
'2020-03-02 06:49:05'
And the process completion date:
'2020-03-02 07:05:02'
Question:
What is the most correct way from the point of view of the approach - to calculate the difference (in minutes) between the start and finish of the process?
(if there are any built-in methods for this in vue.js ornuxt.js, it will be very interesting to learn about them as well.)
I think the best way would be to use Javascript Date object,
d1 = '2020-03-02 06:49:05'
d2 = '2020-03-02 07:05:02'
diff_in_millis = Math.abs(new Date(d1) - new Date(d2))
diff_in_minutes = diff/60000
I suggest using momentjs, you can do something like this:
var duration = moment.duration(endTime.diff(startTime));
var minutes = duration.minutes();
More about duration in momentjs can be found here
Create the date from the string using Date.parse(). It return the date in milliseconds, get the difference and convert that to Minutes.
See snippet below.
const startTime= Date.parse('2020-03-02 06:49:05')
const endTime = Date.parse('2020-03-02 07:05:02')
// Difference in Minutes
const durationInMin= (endTime-startTime)/60000;
console.log({ startTime, endTime, durationInMin })
alert(`Process took: ${durationInMin} minutes`)
Note: For human readable dates, I have found date-fns to be the most helpful. Given its lightweight compared to momentjs. And you could complete the same with the following.
import { differenceInMinutes } from 'date-fns';
const startDate = '2020-03-02 06:49:05';
const endDate = '2020-03-02 07:05:02';
const durationInMin = differenceInMinutes( new Date(endDate), new Date(startDate));
console.log(`Duration: ${durationInMin} minutes`);
At the cost of another dependence to the project of course, but if you are handling lots of human readable dates, it's worth it.
I have a date in UTC in javascript, and I would like to substract some hours.
I searched online and apparently I should concat the substraction to the date like the following:
const diff = "-5"
const utcDate = "2017-02-22 17:28:13"
const date = new Date(utcDate + diff[0] + ' ' + diff[1])
//desired output: 2017-02-22 12:28:13
But I can't seem to make it work.
I do all my Date calculations with .getTime().
So an hour is 3600000 milliseconds.
const MILLISECONDS_HOUR = 3600000;
const diff = -5;
const utcDate_str = "2017-02-22 17:28:13";
const utcDate = new Date( utcDate_str );
const minus_5_hours = new Date( utcDate.getTime() + ( MILLISECONDS_HOUR * diff ));
console.log( utcDate.toJSON());
console.log( minus_5_hours.toJSON());
The big advantage is that javascript will take care of leap years, month boundaries and such.
But since you are calling your variable diff, are you trying to calculate lcoal time vs UTC time?
In that case, reread the javascript Date methods. There's a bunch of methods to handle both UTC and local time, for example: date.getUTCDate() and date.getDate().
So you might not have to calculate all of this yourself.
Also, if you format your dates according to the ISO, "2017-02-22T17:28:13.000Z", this will automatically get parsed as UTC.
someDate.setHours(someDate.getHours()+1);
From https://stackoverflow.com/a/1050782/537998
var startdate = '02.05.2018 18:05:03';
How to find out how many minutes have passed from startdate to now?
My try
var exp = moment(startdate);
minutes = moment().diff(exp, 'minutes');
but result 124764 it not right
Parsing of date strings are not consistent among browsers. Always pass the format of the string if it is in non-ISO format to prevent unwanted bugs:
var exp = moment(startdate, 'DD.MM.YYYY HH:mm:ss');
moment().diff(exp, 'minutes');
To get the difference between two moment time objects, you can use .diff(). Then you can use any of asHours(), asMinutes(), asSeconds() to get human-readable time difference.
var start = moment('02.05.2018 18:05:03');
var end = moment('02.05.2018 18:11:03');
var duration = moment.duration(end.diff(start));
var mins = duration.asMinutes();
console.log(mins)
In your case, you can simply call moment().diff(time) since you want to get difference between the time you specify and now.
var time = moment('02.05.2018 18:05:03');
var duration = moment.duration(moment().diff(time));
var mins = duration.asMinutes();
console.log(mins)
I have the following data:
var currentTime: 2013-07-11 15:55:36+00:00
var currentTimezone: Africa/Asmera
I need a way to convert the currentTime in UTC to a new time based on currentTimezone.
I've looked into Timezone.js and I'm having trouble implementing it (the directions on the site are a little ambiguous)
The code for the function I'm intending on using is included. Thanks :)
<script>
$("#storeTime").click(function(){
storeCurrentTime();
})
$("#getTime").click(function(){
retrieveTime();
})
$("#storeTimezone").click(function(){
var yourTimezone = $('#timezone-select').find(":selected").text();
tz = yourTimezone.toString();
storeCurrentTimezone(tz);
})
$("#convertTime").click(function(){
//get the most recent UTC time, clean it up
var currentTime = $('#RetrievedTime').html();
currentTime = currentTime.split(": ")[1];
$('#convertedTime').html("Converted Time: " + currentTime);
//get the saved timezone
var currentTimezone = $('#storedTimezone').html();
})
</script>
You're going to need to know the timezone offset, so some sort of dictionary with strings to numbers.
// assuming your dictionary says 3 hours is the difference just for example.
var timezoneDiff = 3;
Then you can just make a new time like this
// Assuming you have the proper Date string format in your date field.
var currentDate = new Date(currentTime);
// Then just simply make a new date.
var newDate = new Date(currentDate.getTime() + 60 * 1000 * timezoneDiff);
Update
I've written a javascript helper for this which you can find at:
http://heuuuuth.com/projects/OlsonTZConverter.js
I pulled the timezone data from the wikipedia page https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Usage is as follows once included the script.
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera");
or if there is Daylight Savings in effect:
var offset = OlsonTZConverter.GetUTCOffset("Africa/Asmera",true);
These will throw if you pass an invalid timezone, but you can check if a timezone is valid with:
var isValid = OlsonTZConverter.Contains("Africa/Asmera");
or just look at the entire dictionary with:
var tzDict = OlsonTZConverter.ListAllTimezones();
Hope this maybe saves someone some time sometime :).