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);
Related
I am using the following function to convert my date in RFC3339. I want it to convert in upper limit.
Can anyone assist me, how do I convert it to upper limit?
const date = new Date();
// RFC 3339 format
const targetTime = date.toISOString();
Current output is:
2022-12-20T05:26:12.968Z
Expected output should be
2022-12-20T06:00:00Z
See this answer, very similar but you can replace Math.round with Math.ceil to round up like you want and in addition you'll need to get the percentage the hour is complete (assuming you don't want to round up exact hours).
const milliSecondsInHour = 60*60*1000;
const roundDateToNextHour = (date: Date) => {
const percentHourComplete = (x.getTime() % milliSecondsInHour) / milliSecondsInHour;
date.setHours(date.getHours() + Math.ceil(percentHourComplete));
date.setMinutes(0, 0, 0); // Resets also seconds and milliseconds
return date;
}
If the intention is to the next full UTC hour, test if UTC minutes, seconds or milliseconds are greater than zero. If any of them are, increment the hour and zero the other values, e.g.:
// If the provided date is not exactly on the UTC hour,
// return a date that is the next full UTC hour after
// the provided date.
function toFullUTCHour(date) {
let d = new Date(+date);
d.setUTCHours(d.getUTCHours() + (d.getUTCMinutes() || d.getUTCSeconds() || d.getUTCMilliseconds? 1 : 0), 0,0,0);
return d;
}
let d = new Date()
console.log(d.toISOString() + '\n' +
toFullUTCHour(d).toISOString());
// Simplified version, only works in general for UTC hour
function ceilUTCHour(date = new Date()) {
let d = new Date(+date);
d.setHours(d.getHours() + (d%3.6e6? 1 : 0), 0, 0, 0);
return d;
}
console.log(ceilUTCHour(d).toISOString());
Since, in ECMAScript, UTC days are always exactly 8.64e7 ms long and hours are always exactly 3.6e6 ms long, you can just get the remainder of the current UTC time value and if it's not zero (which will be almost always) add 1 to the UTC hour, then zero the minutes seconds and milliseconds as for the ceilUTCHour function above.
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;
I have a form in which the user selects a date, time and a timezone.
Example:
let date = '02.09.2020';
let time = '16.00';
let timezone = '-07.00';
I want to convert this date with timezone : '+02.00';
I have a hidden text input in which i pass the actualized date format i want.
I don't want to use momment.js for such a small thing.
You could construct a UTC date with an offset of the given timezone -07.00. Then you can add the desired offset of +02.00 to that.
Update: I am going to assume the following, based on other user's input.
Local date: 2020-02-09 16.00 -07:00
UTC date: 2020-02-09 23:00 (subtract the local timezone offset)
UTC +2: 2020-02-10 01:00 (add the desired offset)
const offsetDate = (dateStr, timeStr, srcOffset, destOffset) => {
const tokenize = str => str.split('.').map(v => parseInt(v, 10));
const [ month, date, year ] = tokenize(dateStr);
const [ hour, minute ] = tokenize(timeStr);
const [ srcOffHours, srcOffMins ] = tokenize(srcOffset);
const [ destOffHours, destOffMins ] = tokenize(destOffset);
const utcDate = new Date(Date.UTC(year, month - 1, date, hour, minute));
const srcOff = srcOffHours * 36e5 + srcOffMins * 6e4;
const destOff = destOffHours * 36e5 + destOffMins * 6e4;
utcDate.setTime(utcDate.getTime() - srcOff + destOff);
console.log(`Time: ${utcDate.toISOString()}`);
return [
utcDate.getUTCDate(),
utcDate.getUTCMonth() + 1,
utcDate.getUTCFullYear().toString().substr(2)
].map(v => (v + '').padStart(2, '0')).join(':');
};
const date = '02.09.2020';
const time = '16.00';
const timezone = '-07.00';
console.log(offsetDate(date, time, timezone, '+02.00')); // 10:02:20
You can do something like this
let date = new Date();
let event = date.toLocaleString('ko-KR', { timeZone: 'UTC' })) // if the timezone was Korea
I have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?
I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.
Prefix it with a date:
var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the start of the day;
Or, if you need it to be today's date:
var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the epoch.
You can add the following function that does the job for you :
function getDateFromHours(time) {
time = time.split(':');
let now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));
To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.
Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.
let timeString = "01:12:33";
Extract values with RegEx
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
Convert HH, MM and SS to milliseconds
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
In relation to another point in time, a reference time has to be given.
For instance,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)
How can i convert day date (for example, 22 which stands for 1/22/2017) to Unix Timestamp (after conversion result needs to be 1485079018) in javascript.
I tried code below without luck.
var d = new Date();
var n = d.getDate();
var g = Math.round(new Date().getDate()/1000);
to Unix Timestamp (after conversion result needs to be 1485079018
The Unix timestamp 1485079018 is Jan 22 2017 at 09:56:58 UTC. Where are you getting that 09:56:58 from?
In terms of the problem, if I assume you actually want midnight UTC rather than 09:56:58, see comments:
var day = 22;
// Create the date (in UTC)
var dt = new Date(Date.UTC(2017, 0, day));
// Or not UTC, but then we get really far afield of Unix timestamps:
//var dt = new Date(2017, 0, day);
var ts = Math.round(dt / 1000);
console.log(ts);