So i am trying to get how many seconds there between a ISO date and current time.
My attempt looks like this:
var date = new Date('2018-01-20T15:45:16.698Z').getTime();
var now = Date.now();
var timeLeft = date - now;
var timeLeftInSeconds = Math.floor(timeLeft/ 1000);
but i am getting an incorrect difference and i assume it becuase that ISO dates are UTC while Date.now() are local time. but now sure how to work around this issue?
Related
I'm using momentJS to get difference between 2 dates. Here is my code:
const createdAt = "2019-11-15 09:45:21"; // Sample data from mysql database
// Add time since created
const created = moment(createdAt);
const now = moment();
// get the difference between the moments
const diff = now.diff(created);
//express as a duration
const diffDuration = moment.duration(diff);
const days = diffDuration.days().toString().padStart(2, 0);
const hours = diffDuration.hours().toString().padStart(2, 0);
const minutes = diffDuration.minutes().toString().padStart(2, 0);
With that code, I can properly get the days, hours and minutes difference. The server where mysql is installed is in the Philippines and the createdAt value is automatically generated by mysql.
Now when I try to change my PC's timezone, I get incorrect date difference. I get negative values.
I tried doing something like adding utc():
const created = moment.utc(createdAt);
const now = moment.utc();
And I still don't get any correct values. Am I missing something? Is it possible to do this? Thanks in advance.
The createdAt time above is not UTC format so you will need to update the value by adding/subtracting the hours from your local time, or utc time. It's best to convert the relevant dates to UTC and then perform your diff from there.
Take a look at the options below for parsing and values:
// utc time now
const utcTime = moment.utc();
console.log(utcTime.toString());
// time recorded at server
const philliTime = moment('2019-11-15 09:45:21', 'YYYY-MM-DD HH:mm:ss');
console.log(philliTime.toString());
// need to add 8 hours as philli is +8 hours
philliTime.add(8, 'h');
console.log(philliTime.toString());
// options using parseZone
const optionBPhilli = moment.parseZone('2019-11-15 09:45:21 +08:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBPhilli.toString());
const optionBUTC = moment.parseZone('2019-11-15 09:45:21 +00:00', 'YYYY-MM-DD HH:mm:ss ZZ');
console.log(optionBUTC.toString());
console.log(optionBPhilli.diff(optionBUTC, 'h'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
For more info on parsing the string, check the moment docs and also look at UTC parsing.
I'm trying to use moment.js to compare a date stored in the database (which is set to Europe/London timezone) against the current users time, taking into account their timezone.
I get a date string returned from the database and want to use the fromNow() function, as follows:
console.log(dbDate);
console.log(moment().format());
console.log(moment(dbDate).fromNow());
// DB stored time (Europe/London)
// 2017-09-26 06:56:26
// Current user time (timezone is Pacific Time / Los Angeles)
// 2017-09-25T23:59:03-07:00
// String output by fromNow() function, which should reflect the timezone difference but doesn't
// in 7 hours
I want the fromNow() string to take account the timezone difference and this should always be a time "ago" as opposed to in the future.
I'm probably missing something quite obvious with the library, so apologies in advance if this is very simple.
// get the current time so we know which offset to take
var now = moment.utc();
// get the zone offsets for this time, in minutes
var NewYork_tz_offset = moment.tz.zone("America/New_York").offset(now);
var MY_DATE = moment(dbDate);
// calculate the difference in hours
console.log((NewYork_tz_offset - MY_DATE) / 60);
Does this help your cause?
You have to use moment timezone, you can parse dbDate specifying "Europe/London" timezone using moment.tz:
The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.
Then you can use moment diff and fromNow.
Here a live example:
var dbDate = "2017-09-26 06:56:26";
var now = moment();
var momDbDate = moment.tz(dbDate, "Europe/London");
var pacificTime = moment("2017-09-25T23:59:03-07:00");
console.log(dbDate);
console.log(moment().format());
console.log(momDbDate.fromNow());
console.log(momDbDate.diff(now, 'hours'));
console.log(momDbDate.diff(pacificTime, 'hours'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
I get a date as String from server like this: 2017-01-23T16:08:45.742Z. I want to find the difference in days, between this and the current date (or precisely, current time). I could just extract date alone (without time) and check, but I'd need a precise answer based on provided time & current time.
How do I achieve this?
Should be easy....
var dateFromServer = '2017-01-23T16:08:45.742Z'
var msInDay = 1000 * 60 * 60 * 24
var difference = (new Date(dateFromServer) - Date.now()) / msInDay
document.write('difference = ' + difference + ' days')
That date format looks like ISO_8061. https://en.wikipedia.org/wiki/ISO_8601
Use the Date object to get the difference between today and the other date in milliseconds, then divide by the number of milliseconds in a day.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
The code below can be condensed into a single line but I wanted to be explicit.
let date = "2017-01-23T16:08:45.742Z";
let d1 = new Date(date); // given date
let today = new Date(); // today's date
let diff = (d1 - today); // difference in milliseconds
let days = diff / 8.64e+7; // divide difference by 1 day in milliseconds
console.log(days)
Point of clarification: if I understand you correctly, you're actually trying to get the difference between two dates of different formats, not two dates of unknown formats. That's way easier.
Further, it looks like your server string is already stored in ISO format, which again makes this way easier.
I'd recommend looking at the JavaScript Date object. I believe in this case your best bet would be something like this:
// Your string from the server
var data_from_server = '2017-01-23T16:08:45.742Z';
// Create a new Date() object using the ISO string provided by your server
var olddate = new Date(data_from_server);
// Create a new empty Date() object, which should default to the current time
var currentdate = new Date();
// Subtract the two
var dif = currentdate.getTime() - olddate.getTime();
// Alert the result
alert(dif);
I need to get the difference (in minutes) from a datetime that I get froma get request in a string format to now.
According to my research, I can use moment.js to do so, but I haven't figured out now.
That format I am getting the date/time to be compared is as:
2017-02-10T20:52:13.885Z
I have already tried to do some operations with moment.js such as
moment().startof(comparedTime).fromNow())
But it returns nothing.
What are the alternatives and the best way to do this?
Can't you just use vanilla javaScript?
var getDate = '2017-02-10T20:52:13.885Z'; //get time from server
var parseDate = new Date(getDate).getTime(); //change string into Date object into milliseconds
var nowDate = Date.now(); //get current Date in milliseconds
var minutes = Math.round((nowDate-parseDate)/1000/60); //subtract times, count seconds (/1000), count minutes (/60)
console.log(minutes);
You need to create a moment object by passing the date string in. e.g.
myDate = moment(myISOString)
https://momentjs.com/docs/#/parsing/
Then you can use the moment object as described in the docs.
With Moment.js, this is simply:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes') // 65
If you want partial minutes included, then pass true as a third parameter:
moment().diff('2017-02-10T20:52:13.885Z', 'minutes', true) // 65.04565
I want to create Start and End Time stamp using Moment.js (EST):
StartTime would be today's start time
EndTime would be current time.
I have used moment.js and created like this
var time = new Date();
var startTime=Date.parse(moment(time).startOf('day').tz('America/New_York').format("MM/DD/YYYY HH:mm:ss"));
var endTime=Date.parse(moment(time).tz('America/New_York').format("MM/DD/YYYY HH:mm:ss"));
It is giving time in milliseconds.
Is it correct or wrong?
I am not getting data from db because there is mismatch in Time stamp.
First thing first, when you use momentjs, STOP using Date explictly:
var moment = require('moment-timezone');
// moment() without parameter means the current time
// toDate() converts the moment object to a javascript Date
var startTime = moment().tz('America/New_York').startOf('day').toDate();
var endTime = moment().tz('America/New_York').toDate();
// startTime and endTime are Date objects
console.log(startTime);
console.log(endTime);