Javascript find time difference in hours with timezone - javascript

I have a javascript object with the following details:
var dateobj = {
date: "2020-12-21 03:31:06.000000",
timezone: "Africa/Abidjan",
timezone_type: 3
}
var date = new Date();
var options = {
timeZone: dateobj.timezone
};
var curr_date = date.toLocaleString('en-US', options)
console.log(curr_date)
//I want this
//diff = curr_date - dateobj.date
I want to find the time difference in hours with the current date-time of the same timezone. I know I can use toLocaleString() function to get the date-time string in a particular timezone, but how can I find the time difference? The above code gets the current date time in that timezone, how can I find the time difference in hours?

In general when working with dates in JS I usually use a library called date-fns (Date functions). It just makes dates and time a lot easier to manage. This is how you would get the time difference in hours with date-fns.
const { differenceInHours } = require("date-fns");
const { zonedTimeToUtc } = require("date-fns-tz");
const timeData1 = {date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3};
const timeData2 = {date: "2020-12-21 03:31:06.000000", timezone: "America/Los_Angeles", timezone_type: 3};
const t1 = zonedTimeToUtc(timeData1.date, timeData1.timezone);
const t2 = zonedTimeToUtc(timeData2.date, timeData2.timezone);
const diff = differenceInHours(t2, t1);
console.log(diff);
// => 8
Run demo: https://runkit.com/embed/jtfu0ixxthy7

Related

Time changes after toLocaleTimeString()

I'm using a google sheets script, which on the click of a button will add values to two fields.
The first will contain the date, the second the time.
For this, I use this piece of code:
var timestamp = new Date();
var date = Utilities.formatDate(timestamp, "GMT+1", "dd/MM/yyyy");
var time = timestamp.toLocaleTimeString('nl-BE');
Now, the issue is that the time is off by 6 hours.
The timestamp value does contain the correct time, the date variable gets the correct date, but the time seems to differ 6 hours after the 'toLocaleTimeString() function.
Use Utilities.formatDate() for time as well, like this:
const timezone = SpreadsheetApp.getActive().getSpreadsheetTimeZone(); // or 'GMT+1'
const timestamp = new Date();
const dateString = Utilities.formatDate(timestamp, timezone, 'dd/MM/yyyy');
const timeString = Utilities.formatDate(timestamp, timezone, 'HH:mm:ss');
console.log(`date and time in ${timezone}: ${dateString} ${timeString}`);

Display and Formatting UTC Time On Static Website in Real-Time

My website currently displays UTC time like this:
2022-03-22T23:38:25.748Z
But I would like for it to be formatted like this:
23:39:22 UTC
Here is the javascript I have:
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var x = new Date()
var x1=x.toISOString();// changing the display to UTC string
document.getElementById('ct').innerHTML = x1;
tt=display_c();
}
<body onload=display_ct();><span id='ct' >
Can you help me format this? I've looked into using angular and searched other methods for implementing this but it seems that there are many ways to do this. The things I've tried do not display the format correctly. The code above is the closest solution I have found.
This should produce the format you want to have.
let date = new Date();
let utc_string = date.toUTCString().match(/..:..:.. .*/)[0];
console.log(utc_string);
new Date().toISOString().slice(11, 19) + ' UTC'
A nice and intentional property of the ISO datetime format is that most of the parts are always the same length.
Note that truncating, not rounding, is the correct behavior.
Use the Intl.DateTimeFormat method for this as follows:
function display_c(){
const refresh = 1000;
mytime = setTimeout('display_ct()',refresh)
}
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "long" });
document.getElementById('ct').innerHTML = dtf.format( new Date() );
tt = display_c();
}
display_ct();
<div id="ct"></div>
Customization:
You can either use the various configuration options available to customize the format of the datetime, or use the following setup for displaying a custom String:
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "medium" });
document.getElementById('ct').innerHTML = dtf.format( new Date() ) + " Zulu";
}
Available configuration options: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
I found a web to helping you. And i give an example to you too.
https://www.codevscolor.com/javascript-iso-utc
const date = new Date('2022-03-22T23:38:25.748Z')
console.log(date.toString())
console.log(date.toUTCString())

How to use startOfDay from date-fns with timezones?

I try to replace momentjs with date-fns
but I am struggling with a very simple thing:
I need to calculate startOfDay, end of day and addDays for the dates that I have got in timestamps and according to the giving timezone.
date = 1492437600; // Monday April 17, 2017 12:00:00 (pm) in time zone America/Noronha
timeZone = 'America/Noronha';
_startOfDay = utcToZonedTime(startOfDay(date*1000), timeZone).getTime()/1000;
and I have got the result for the _startOfDay = 1492365600 that is Sunday April 16, 2017 16:00:00 (pm) in time zone America/Noronha
What I am doing wrong?
thanks in advance
Note: See the bottom of this answer for the best solution
Old Answer:
I see this question is 11 months old (as of writing) but thought I'd answer it as I hit the same problem, and others may come here in the future with the same question.
The date-fns library doesn't have timezone support, so you need to also use the date-fns-tz library. Import the getTimezoneOffset function from date-fns-tz and use to calculate the offset between the local (browser) timezone and the timezone you wish to calculate end of day for (i.e. America/Noronha). Note that the date-fns "endOf" functions use the local/browser timezone.
E.g.
import { endOfDay } from 'date-fns';
import { getTimezoneOffset } from 'date-fns-tz/esm';
const MILLISECS_IN_DAY = 86400000;
const localTz = Intl.DateTimeFormat().resolvedOptions().timeZone; // Browser Timezone
const tzOffset = getTimezoneOffset('America/Noronha') - getTimezoneOffset(localTz);
// Have to cater for negative offsets
const tzOffsetEOD = (tzOffset < 0) ? (MILLISECS_IN_DAY + tzOffset) : tzOffset;
let testDate = new Date();
let eodInTimezone = endOfDay(testDate).getTime() - tzOffsetEOD; // in millisecs
// Have to project forward a day if the result is in the past
if (eodInTimezone < testDate.getTime()) eodInTimezone += MILLISECS_IN_DAY;
Someone may be able to come up with a more elegant solution to this problem. If I do I'll post back here.
New Answer:
This solution works best for all "End Of" date-fns functions:
import { endOfDay, endOfWeek, endOfMonth, endOfYear } from 'date-fns';
import { utcToZonedTime, zonedTimeToUtc } from 'date-fns-tz/esm';
const calcZonedDate = (date, tz, fn, options = null) => {
const inputZoned = utcToZonedTime(date, tz);
const fnZoned = (options) ? fn(inputZoned, options) : fn(inputZoned);
return zonedTimeToUtc(fnZoned, tz);
}
const getZonedEndOfDay = (date, timeZone) => {
return calcZonedDate(date, timeZone, endOfDay);
}
const getZonedEndOfWeek = (date, timeZone) => {
return calcZonedDate(date, timeZone, endOfWeek, { weekStartsOn: 1 });
}
const getZonedEndOfMonth = (date, timeZone) => {
return calcZonedDate(date, timeZone, endOfMonth);
}
const getZonedEndOfYear = (date, timeZone) => {
return calcZonedDate(date, timeZone, endOfYear);
}
// Example Usage
let endOfDayZoned = getZonedEndOfDay(new Date(), 'America/Noronha');
Hope this helps.

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

Get timestamp from date string without timezone and timezone name apart

I have a dateTime string in this (bad, I know) format coming from an external API:
const startDate = '2/13/2020 15:00';
and the timezone name:
const timezoneName = 'America/New_York';
Which means that the dateTime is 2/13/2020 15:00 in New York.
Any idea for an elegant way to get timestamp (or JavaScript date object)?
I don't mind using moment.js or/and moment-timezone if it helps.
Moment and Moment-Timezone are for legacy code.
For new applications, the Moment team recommends Luxon.
const startDate = '2/13/2020 15:00';
const timezoneName = 'America/New_York';
const dateTime = luxon.DateTime.fromFormat(startDate, 'M/d/yyyy HH:mm',
{ zone: timezoneName });
const utcDateTime = dateTime.toUTC();
const s = utcDateTime.toISO();
console.log(s); //=> "2020-02-13T20:00:00.000Z"
Using moment-timezone should work:
const moment = require('moment-timezone');
const t = moment.tz("2/13/2020 15:00", "MM/DD/YYYY HH:mm","America/New_York");
console.log(t.toISOString()); // Prints '2020-02-13T20:00:00.000Z'

Categories

Resources