I have a variable called lastMessageTimestamp which contains string representing a timestamp that is in UTC: "2022-07-07T11:05:53.209"
I need to compare the time now to the time stored lastMessageTimestamp.
// returns unix epoch of utc time now
const nowDateTime = Date.now();
const lastMessageDateTime = new Date(lastMessageTimestamp);
const lastMessageUnixEpoch = Date.UTC(
lastMessageDateTime.getUTCFullYear(),
lastMessageDateTime.getUTCMonth(),
lastMessageDateTime.getUTCDate(), lastMessageDateTime.getUTCHours(),
lastMessageDateTime.getUTCMinutes(), lastMessageDateTime.getUTCSeconds()
);
const difference = (nowDateTime - lastMessageUnixEpoch) / 1000;
The problem with this code is when I call new Date(lastMessageTimestamp); my timezone is added (GMT+1) so then when I try and create the lastMessageInUnixEpoch the timezone is included and my difference var is a whole hour out.
How can I get lastMessageTimestamp in to a unix timestamp that doesn't include any timezone so that I can compare it to the unix timestamp that is defined on the nowDateTime var?
You can use new Date(lastMessageTimestamp + 'Z') to ensure it's interpreted as an UTC timestamp:
const nowDate = new Date();
const lastMessageDate = new Date(lastMessageTimestamp+'Z');
const difference = (nowDate.getTime() - lastMessageDate.getTime()) / 1000;
or
const nowDateMillis = Date.now();
const lastMessageDateMillis = Date.parse(lastMessageTimestamp+'Z');
const difference = (nowDateMillis - lastMessageDateMillis) / 1000;
Related
How can I extract time only as a unix number from a unix timestamp?
For example:
const timeStamp = 1671682809 // Thursday, December 22, 2022 11:20:09 AM GMT+07:00
const unixTimeOnly = extractTime(timeStamp) // return a unix number that represents "11:20:09"
Thank you!
You could do this by subtracting the same date, with the clock set to midnight:
const timeStamp = 1671682809;
const date = new Date(timeStamp * 1000);
const midnightDate = new Date(date).setHours(0,0,0,0);
const justHMS = date - midnightDate;
// you may want to divide this number how you wish if you're not working in milliseconds
console.log(justHMS);
I'm trying to get a difference between two dates in seconds. The logic would be like this :
set an initial date which would be now;
set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
get the difference between those two ( the amount of seconds )
The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.
I've been trying something like this :
var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)
The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.
The explanation
You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00
Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.
For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.
Useful docs for this answer
Why 1970?
Date object
Date's getTime method
Date's getDate method
Need more accuracy than just seconds?
You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
Below code will give the time difference in second.
import Foundation
var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
alert(timeDiffInSecond );
<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
time difference between now and 10 minutes later using momentjs
let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;
let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);
to get the difference between the dates in seconds ->
let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);
but this porduces results in utc(for some reason that i dont know).
So you have to take account for timezone offset, which you can do so by adding
new Date().getTimezoneOffset();
but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.
let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);
This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.
Define two dates using new Date().
Calculate the time difference of two dates using date2. getTime() – date1. getTime();
Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
const getTimeBetweenDates = (startDate, endDate) => {
const seconds = Math.floor((endDate - startDate) / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return { seconds, minutes, hours, days };
};
try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);
I have hours and minutes in firebase format (can't change this): 2230
I need to convert this to normal date, year, day and month are current time, only hour and minutes are specifed
var startDate = new Date();
I need to set date something like this:
startDate.setHours(myhours, myminutes, myday, 0);
An easy way to do this is to create a new Date, then just update those values:
const hours = 15; // 24-hour format, 0 = midnight, 15 = 3PM
const minutes = 45;
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
This will give you a Date object with the current time (as defined by the client's computer), but with the hours and minutes set to what you specify, and seconds set to 0 (since having 15:45:58 is weird).
To convert the string to variables, just do this:
const [, hours, minutes] = '2230'.match(/(\d{2})(\d{2})/).map(m => parseInt(m));
console.log(hours, minutes);
const d = new Date();
d.setHours(hours);
d.setMinutes(minutes);
d.setSeconds(0);
console.log(d);
Keep in mind that it will assume you are setting it based on GMT (timezone offset +0000). If you want it relative to your time, either change the date object (if you just need its values to match) or shift it by your timezone offset.
const hour = 15;
const minute = 45;
const d = new Date();
d.setHours(hour - (d.getTimezoneOffset() / 60)); // adjust hour to local timezone
d.setMinutes(minute);
d.setSeconds(0);
console.log(d);
I want to calculate the difference between two dateTime, one date is submitted by user and other is current time:
user submitted time - now = difference in unix
user submitted time format is:
2014-03-26 10:52:00
Thanks for your help.
You can simply do this with getTime() which returns the number of milliseconds.
var ds = "2014-03-26 10:52:00";
var newDate = new Date(ds).getTime(); //convert string date to Date object
var currentDate = new Date().getTime();
var diff = currentDate-newDate;
console.log(diff);
Sometimes there are chance for cross browser compatibility in parsing the date string so it is better to parse it like
var ds = "2014-03-26 10:52:00";
var dateArray = ds.split(" "); // split the date and time
var ds1 = dateArray[0].split("-"); // split each parts in date
var ds2 = dateArray[1].split(":"); // split each parts in time
var newDate = new Date(ds1[0], (+ds1[1] - 1), ds1[2], ds2[0], ds2[1], ds2[2]).getTime(); //parse it
var currentDate = new Date().getTime();
var diff = currentDate - newDate;
console.log(diff); //timestamp difference
You can use MomentJS library
var user_submited_time = moment('2014-03-26 10:52:00');
var now = moment();
var value = user_submited_time - now;
I need to format a date as yyyy-MM-dd'T'HH:mm:ss.SSS'Z' as specified by Parse's REST API for Facebook. I was wondering what the most lightweight solution to this would be.
Call the toISOString() method:
var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());
// Output:
// 2010-07-30T15:05:00.000Z
toISOString() will return current UTC time only not the current local time. If you want to get the current local time in yyyy-MM-ddTHH:mm:ss.SSSZ format then you should get the current time using following two methods
Method 1:
console.log(new Date(new Date().toString().split('GMT')[0]+' UTC').toISOString());
Method 2:
console.log(new Date(new Date().getTime() - new Date().getTimezoneOffset() * 60000).toISOString());
function converToLocalTime(serverDate) {
var dt = new Date(Date.parse(serverDate));
var localDate = dt;
var gmt = localDate;
var min = gmt.getTime() / 1000 / 60; // convert gmt date to minutes
var localNow = new Date().getTimezoneOffset(); // get the timezone
// offset in minutes
var localTime = min - localNow; // get the local time
var dateStr = new Date(localTime * 1000 * 60);
// dateStr = dateStr.toISOString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); // this will return as just the server date format i.e., yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
dateStr = dateStr.toString("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
return dateStr;
}
Add another option, maybe not the most lightweight.
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
<script src="https://cdn.jsdelivr.net/npm/dayjs#1.9.7/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dayjs#1.9.7/plugin/customParseFormat.js"></script>
Node.js
const offsetInMinutes = 2 * 60 ; //Romanian
const todaysDate = new Date(new Date().getTime() + offsetInMinutes * 60000).toISOString();
You can use javax.xml.bind.DatatypeConverter class
DatatypeConverter.printDateTime
&
DatatypeConverter.parseDateTime