I am calculating Over Time from work start time & work End time.
We need to calculate Over Time that does not include regular work Timings.
Example: Regular Work Timings is 10:00 AM to 07:00 PM
Over Time need to get from these timings:
Start Work Hour: 13-09-2021 08:00
End Work Hour: 15-09-2021 20:00
We need to calculate total hours outside of 10:00 AM to 07:00 PM from Start Work Hour: 13-09-2021 08:00 & End Work Hour: 15-09-2021 20:00
So, here Total OT would be: 32 Hour
What I have tried?
If work Start time and End time in the same day, OT calculation works fine with the below code.
Start Hour : 15-09-21 08:00
End Hour : 15-09-21 21:00
getWorkHours.forEach((workhourOT) => {
try {
// --------------------------------------
let StartWorkHour = moment(
workhourOT.starttime,
"DD-MM-YYYY hh:mm:ss"
);
let TodayOfficeStartDate =
moment(StartWorkHour).format("DD-MM-YYYY");
let StartOfficeHour = moment(
`${TodayOfficeStartDate}` + ` 10:00:00`,
"DD-MM-YYYY hh:mm:ss"
);
const diffInMillisecondsBeforeOfficeHour = Math.abs(
new Date(StartWorkHour) - new Date(StartOfficeHour)
);
let OTBeforeOffice =
diffInMillisecondsBeforeOfficeHour / 1000 / 3600;
console.log(OTBeforeOffice);
let EndtWorkHour = moment(
workhourOT.endtime,
"DD-MM-YYYY hh:mm:ss"
);
let TodayOfficeEndDate =
moment(EndtWorkHour).format("DD-MM-YYYY");
let EndOfficeHour = moment(
`${TodayOfficeEndDate}` + ` 19:00:00`,
"DD-MM-YYYY hh:mm:ss"
);
const diffInMillisecondsAfterOfficeHour = Math.abs(
new Date(EndtWorkHour) - new Date(EndOfficeHour)
);
let OTAfterOffice =
diffInMillisecondsAfterOfficeHour / 1000 / 3600;
console.log(OTAfterOffice);
let totalWORKOT = OTAfterOffice + OTBeforeOffice;
data["TotalWork_OT"] = totalWORKOT.toFixed(1);
} catch (error) {
console.log(error);
}
});
OutPut is
{
"TotalWork_OT": "4.0",
}
There is a lot of logic missing from the OP to achieve the required result. Consider an approach where a workHours object {startTime, endTime} is enhanced with an overtime property.
For each workHours object the following cases need to be addressed, where nominal start and end are normal hours (10:00 to 19:00):
start and end before nominal start
start and end after nominal start
start before, end during nominal hours
start during and end after nominal hours
start and end during nominal hours
In addition, it needs to account for times going over midnight and likely also skip weekends.
The OP assumes work starts before nominal start and ends after nominal end, so the below example does the same. So it only addresses one of the above cases, and has virtually no error handling, but it should provide an idea of what's required to do the job.
It takes a work hours object and returns a new object augmented with an overtime property and the overtime hours in the range. It only deals with whole hours and where work start and end are before and after nominal start and end respectively.
Each helper function can be extended with required additional functionality to handle the other cases and deal with partial hours (maybe round to 15 minute increments).
// Parse timestamp in DD-MM-YYYY HH:mm format
// Values after day are optional and default to zero (0)
function parseWorkHour(wh) {
let [D, M, Y, H, m, s] = wh.split(/\W/);
return new Date(Y, M-1, D, H||0, m||0, s||0);
}
// Format date as DD-MM-YYYY HH:mm
function formatWorkHour(date) {
let z = n => ('0'+n).slice(-2);
return `${z(date.getDate())}-${z(date.getMonth()+1)}-` +
`${date.getFullYear()} ${z(date.getHours())}:` +
`${z(date.getMinutes())}`;
}
// Return true if date1 and date2 are same day
function areSameDay(d1, d2) {
return !isNaN(d1) && !isNaN(d2) &&
d1.getFullYear() == d2.getFullYear() &&
d1.getMonth() == d2.getMonth() &&
d1.getDate() == d2.getDate();
}
// Given workhours object {startTime, endTime} return
// array of daily workHours objects for input object range
function getDailyWorkHours(who) {
let start = parseWorkHour(who.startTime);
let end = parseWorkHour(who.endTime);
let dailyWorkHours = [];
// No validation (e.g. start > end) so guard against infinite loop
let i = 10;
while (!areSameDay(start, end) && --i) {
let temp = new Date(start);
temp.setHours(23,59,59,999);
dailyWorkHours.push({
startTime: formatWorkHour(start),
endTime: formatWorkHour(temp)
});
temp.setHours(24,0,0,0);
start = temp;
}
dailyWorkHours.push({
startTime: formatWorkHour(start),
endTime: formatWorkHour(end)
});
return dailyWorkHours;
}
// Get overtime from workHours object {startTime, endTime}
// startTime and endTime must be same day.
// Overtime is before 10:00 and after 19:00
function getOvertime(who) {
let workStart = parseWorkHour(who.startTime);
let workEnd = parseWorkHour(who.endTime);
let officeStart = new Date(+workStart);
officeStart.setHours(10,0,0,0);
let officeEnd = new Date(+workEnd);
officeEnd.setHours(19,0,0,0);
let ot = (officeStart - workStart) / 3.6e6 +
(workEnd - officeEnd) / 3.6e6;
// Round to nearest hour
return Math.round(ot);
}
// Given work hours array [{startTime,endTime}], calculate how
// much overtime has been worked,
// i.e. time before officeStart (10:00) and officeEnd (19:00)
function tallyOvertime(workHoursArray) {
let result = [];
workHoursArray.forEach( who => {
let dailyWorkHours = getDailyWorkHours(who);
let overTime = dailyWorkHours.reduce((ot, who) => {
ot += getOvertime(who);
return ot;
}, 0);
result.push({
startTime:who.startTime,
endTime:who.endTime,
overTime:overTime
});
});
return result;
}
let data = [
// Same day - 5 hrs
{startTime:'20-09-2021 06:00', endTime:'20-09-2021 20:00'},
// Over midnight - 20
{startTime:'20-09-2021 06:00', endTime:'21-09-2021 20:00'},
// OP example - 33
{startTime:'13-09-2021 08:00', endTime:'15-09-2021 20:00'}
];
console.log(tallyOvertime(data));
In the OP there is:
We need to calculate total hours outside of 10:00 AM to 07:00 PM from
Start Work Hour: 13-09-2021 08:00 & End Work Hour: 15-09-2021 20:00
So, here Total OT would be: 32 Hour
Which is incorrect. The breakdown is as follows:
13-09-2021 08:00 to 10:00 is 2 hours
13-09-2021 19:00 to 24:00 is 5 hours
14-09-2021 00:00 to 10:00 is 10 hours
14-09-2021 19:00 to 24:00 is 5 hours
15-09-2021 00:00 to 10:00 is 10 hours
15-09-2021 19:00 to 20:00 is 1 hour
which totals 33 hours, not 32.
I have done something like this.
work Start date: 18-09-21 08:00
work End Date: 20-09-21 20:00
get OT for the work start date to midnight the same day. start: 18-09-21 08:00 ---- end: 18-08-21 24:00
get OT starting from the start day of the work end date to work end time. start: 20-09-21 00:00 --- end: 20-09-21 20:00
on every full day of working we get 15 Hour Overtime excluding regular working hours. so we can multiply the total full day OT with 15. and sum all three results.
OT Function
async function calculateWorkOverTime(TimingArr) {
for (OTI = 0; OTI < TimingArr.length; OTI++) {
try {
let StartWorkHour = moment(
TimingArr[OTI].starttime,
"DD-MM-YYYY hh:mm:ss"
);
let TodayOfficeStartDate = moment(StartWorkHour).format("DD-MM-YYYY");
let StartOfficeHour = moment(
`${TodayOfficeStartDate}` + ` 10:00:00`,
"DD-MM-YYYY hh:mm:ss"
);
const diffInMillisecondsBeforeOfficeHour = Math.abs(
new Date(StartWorkHour) - new Date(StartOfficeHour)
);
let OTBeforeOffice = diffInMillisecondsBeforeOfficeHour / 1000 / 3600;
// console.log(OTBeforeOffice);
let EndtWorkHour = moment(TimingArr[OTI].endtime, "DD-MM-YYYY hh:mm:ss");
let TodayOfficeEndDate = moment(EndtWorkHour).format("DD-MM-YYYY");
let EndOfficeHour = moment(
`${TodayOfficeEndDate}` + ` 19:00:00`,
"DD-MM-YYYY hh:mm:ss"
);
const diffInMillisecondsAfterOfficeHour = Math.abs(
new Date(EndtWorkHour) - new Date(EndOfficeHour)
);
let OTAfterOffice = diffInMillisecondsAfterOfficeHour / 1000 / 3600;
let totalWORKOT = OTAfterOffice + OTBeforeOffice;
return totalWORKOT;
} catch (error) {
return error;
}
}
}
var OT = "";
for (OTArr = 0; OTArr < getWorkHours.length; OTArr++) {
let StartTimingWork = moment(
getWorkHours[OTArr].starttime,
"DD-MM-YYYY hh:mm:ss"
);
let TodayStartTiming = moment(StartTimingWork).format("DD-MM-YYYY");
let EndTimingWork = moment(
getWorkHours[OTArr].endtime,
"DD-MM-YYYY hh:mm:ss"
);
console.log(getWorkHours);
let TodayEndTiming = moment(EndTimingWork).format("DD-MM-YYYY");
if (TodayEndTiming === TodayStartTiming) {
let getOTFROMTIMING = await otcontroller.calculateWorkOverTime(
getWorkHours
);
OT = getOTFROMTIMING;
data["WOT"] = OT;
} else {
// var workstartDate = moment(TodayEndTiming, "DD-MM-YYYY");
var workstartDate = StartTimingWork;
let currentDayMidNight = moment(workstartDate).endOf("day");
let ArrOfTiming = [
{
starttime: workstartDate,
endtime: currentDayMidNight,
},
];
let getOTFROMTIMING = await otcontroller.calculateWorkOverTime(
ArrOfTiming
);
console.log(getOTFROMTIMING);
var workendDate = EndTimingWork;
let startOfWorkEndDate = moment(workendDate).startOf("day");
// console.log(workendDate);
// console.log(startOfWorkEndDate);
let ArrOfTimingEnd = [
{
starttime: startOfWorkEndDate,
endtime: workendDate,
},
];
let getOTFROMTIMINGlastDay =
await otcontroller.calculateWorkOverTime(ArrOfTimingEnd);
console.log(getOTFROMTIMINGlastDay);
// var workendDate = EndTimingWork;
// console.log(workstartDate);
console.log("workendDate");
console.log(workendDate);
console.log(workstartDate);
console.log("workstartDate");
var result = workendDate.diff(workstartDate, "days");
console.log(result);
console.log("result");
let wholeDaysOT = (result - 1) * 15;
console.log(
wholeDaysOT + getOTFROMTIMINGlastDay + getOTFROMTIMING
);
let TotalWorkOverTime =
wholeDaysOT + getOTFROMTIMINGlastDay + getOTFROMTIMING;
data["WOT"] = TotalWorkOverTime.toFixed(1);
}
}
The following gives me the timestamp of the current date-time:
Source
moment().utc().valueOf()
Output
1626964579209 // 2021-07-22T14:36:19Z
How do I get the timestamp of the previous/last 07:00 AM (2021-07-22T07:00:00Z) and 11:00 PM (2021-07-21T23:00:00Z) date-times?
Notice that, in this situation, the last/previous 11:00 PM timestamp is from the previous day (2021-07-21).
I've tried playing around with Moment.js Durations and Subtract Time but without much success.
Here's a StackBlitz to play around: https://stackblitz.com/edit/typescript-ofcrjs
Thanks in advance!
You could do
const currentDateTime = moment().utc();
console.log('Current date-time timestamp:', currentDateTime.valueOf());
console.log('Current date-time string:', currentDateTime.format());
// If the current date-time string is 2021-07-22T14:36:19Z
// then the previous/last 07:00 AM string is 2021-07-22T07:00:00Z and the
// previous/last 11:00 PM string is 2021-07-21T23:00:00Z (previous day)
let last7amTimestamp = currentDateTime.clone().startOf('d').add(7, 'h'); // ???
if (last7amTimestamp.isAfter(currentDateTime)) {
last7amTimestamp.subtract(1, 'd')
}
let last11pmTimestamp = currentDateTime.clone().startOf('d').add(23, 'h'); // ???
if (last11pmTimestamp.isAfter(currentDateTime)) {
last11pmTimestamp.subtract(1, 'd')
}
console.log('Previous/last 07:00 AM timestamp:', last7amTimestamp);
console.log('Previous/last 11:00 PM timestamp:', last11pmTimestamp);
Did you mean like this?
moment('7:00 AM', 'h:mm A').subtract(1,'days').utc().valueOf();
moment('11:00 PM', 'hh:mm A').subtract(1,'days').utc().valueOf();
Just get the time of today and subtract day by 1.
You can test the current UTC hour and if it's after the required hour, just set the UTC hour to the time. If it's before, set it to the hour on the previous day, i.e. hour - 24.
E.g. a general function to get the previous specified hour UTC given a supplied date or default to the current date without moment.js is:
// Get the previous hour UTC given a Date
// Default date is current date
function previousUTCHour(h, d = new Date()) {
// Copy d so don't affect original
d = new Date(+d);
return d.setUTCHours(d.getUTCHours() < h ? h - 24 : h, 0, 0, 0);
}
// Example
let d = new Date();
console.log('Currently : ' + d.toISOString());
[1, 7, 11, 18, 23].forEach(
h => console.log('Previous ' + (''+h).padStart(2, '0') +
' ' + new Date(previousUTCHour(h)).toISOString())
);
I am looking for a function to convert date in one timezone to another.
It need two parameters,
date (in format "2012/04/10 10:10:30 +0000")
timezone string ("Asia/Jakarta")
The timezone string is described in http://en.wikipedia.org/wiki/Zone.tab
Is there an easy way to do this?
Here is the one-liner:
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
// usage: Asia/Jakarta is GMT+7
convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta") // Tue Apr 20 2012 17:10:30 GMT+0700 (Western Indonesia Time)
// Resulting value is regular Date() object
const convertedDate = convertTZ("2012/04/20 10:10:30 +0000", "Asia/Jakarta")
convertedDate.getHours(); // 17
// Bonus: You can also put Date object to first arg
const date = new Date()
convertTZ(date, "Asia/Jakarta") // current date-time in jakarta.
This is the MDN Reference.
Beware the caveat: function above works by relying on parsing toLocaleString result, which is string of a date formatted in en-US locale , e.g. "4/20/2012, 5:10:30 PM". Each browser may not accept en-US formatted date string to its Date constructor and it may return unexpected result (it may ignore daylight saving).
Currently all modern browser accept this format and calculates daylight saving correctly, it may not work on older browser and/or exotic browser.
side-note: It would be great if modern browser have toLocaleDate
function, so we don't have to use this hacky work around.
For moment.js users, you can now use moment-timezone. Using it, your function would look something like this:
function toTimeZone(time, zone) {
var format = 'YYYY/MM/DD HH:mm:ss ZZ';
return moment(time, format).tz(zone).format(format);
}
Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
Stolen shamelessly from: http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/6016329
/**
* function to calculate local time
* in a different city
* given the city's UTC offset
*/
function calcTime(city, offset) {
// create Date object for current location
var d = new Date();
// get UTC time in msec
var utc = d.getTime();
// create new Date object for different city
// using supplied offset
var nd = new Date(utc + (3600000*offset));
// return time as a string
return "The local time in " + city + " is " + nd.toLocaleString();
}
this function is useful to calculate time zone value by providing name of a city/country and offset value
Okay, found it!
I'm using timezone-js. this is the code:
var dt = new timezoneJS.Date("2012/04/10 10:10:30 +0000", 'Europe/London');
dt.setTimezone("Asia/Jakarta");
console.debug(dt); //return formatted date-time in asia/jakarta
If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.
// Specifying timeZone is what causes the conversion, the rest is just formatting
const options = {
year: '2-digit', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
timeZone: 'Asia/Jakarta',
timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")
const dateInNewTimezone = formatter.format(startingDate)
console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7
Offsets, daylight saving, and changes in the past will be taken care of for you.
UPDATE
There is also this new Temporal tool that handles timezones among other things. Like only dates or only time. It's experimental as of now
It's meant to replace the old legacy Date
var isoDate = new Date().toJSON() // eg: '2022-11-18T13:56:09.697Z'
Temporal.Instant.from(isoDate).toZonedDateTimeISO('Europe/Stockholm')
Got it!
Wanted to force the date shown = server date, no mattter the local settings (UTC).
My server is GMT-6 --> new Date().getTimezoneOffset() = 360
myTZO = 360;
myNewDate = new Date(myOldDateObj.getTime() + (60000*(myOldDateObj.getTimezoneOffset()-myTZO)));
alert(myNewDate);
You can use to toLocaleString() method for setting the timezone.
new Date().toLocaleString('en-US', { timeZone: 'Indian/Christmas' })
For India you can use "Indian/Christmas" and the following are the various timeZones,
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
I should note that I am restricted with respect to which external libraries that I can use. moment.js and timezone-js were NOT an option for me.
The js date object that I have is in UTC. I needed to get the date AND time from this date in a specific timezone('America/Chicago' in my case).
var currentUtcTime = new Date(); // This is in UTC
// Converts the UTC time to a locale specific format, including adjusting for timezone.
var currentDateTimeCentralTimeZone = new Date(currentUtcTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
console.log('currentUtcTime: ' + currentUtcTime.toLocaleDateString());
console.log('currentUtcTime Hour: ' + currentUtcTime.getHours());
console.log('currentUtcTime Minute: ' + currentUtcTime.getMinutes());
console.log('currentDateTimeCentralTimeZone: ' + currentDateTimeCentralTimeZone.toLocaleDateString());
console.log('currentDateTimeCentralTimeZone Hour: ' + currentDateTimeCentralTimeZone.getHours());
console.log('currentDateTimeCentralTimeZone Minute: ' + currentDateTimeCentralTimeZone.getMinutes());
UTC is currently 6 hours ahead of 'America/Chicago'. Output is:
currentUtcTime: 11/25/2016
currentUtcTime Hour: 16
currentUtcTime Minute: 15
currentDateTimeCentralTimeZone: 11/25/2016
currentDateTimeCentralTimeZone Hour: 10
currentDateTimeCentralTimeZone Minute: 15
If you just need to convert timezones I have uploaded a stripped-down version of moment-timezone with just the bare minimum functionallity. Its ~1KB + data:
S.loadData({
"zones": [
"Europe/Paris|CET CEST|-10 -20|01010101010101010101010|1GNB0 1qM0 11A0 1o00 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0 WM0 1qM0 11A0 1o00 11A0 1o00 11A0 1qM0 WM0 1qM0|11e6",
"Australia/Sydney|AEDT AEST|-b0 -a0|01010101010101010101010|1GQg0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1fA0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0 1cM0|40e5",
],
"links": [
"Europe/Paris|Europe/Madrid",
]
});
let d = new Date();
console.log(S.tz(d, "Europe/Madrid").toLocaleString());
console.log(S.tz(d, "Australia/Sydney").toLocaleString());
Here is my code, it is working perfectly, you can try with give below demo:
$(document).ready(function() {
//EST
setInterval( function() {
var estTime = new Date();
var currentDateTimeCentralTimeZone = new Date(estTime.toLocaleString('en-US', { timeZone: 'America/Chicago' }));
var seconds = currentDateTimeCentralTimeZone.getSeconds();
var minutes = currentDateTimeCentralTimeZone.getMinutes();
var hours = currentDateTimeCentralTimeZone.getHours()+1;//new Date().getHours();
var am_pm = currentDateTimeCentralTimeZone.getHours() >= 12 ? "PM" : "AM";
if (hours < 10){
hours = "0" + hours;
}
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var mid='PM';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='AM';
}
var x3 = hours+':'+minutes+':'+seconds +' '+am_pm
// Add a leading zero to seconds value
$("#sec").html(x3);
},1000);
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<p class="date_time"><strong id="sec"></strong></p>
</body>
</html>
Set a variable with year, month, and day separated with - symbols, plus a T and the time in HH:mm:ss pattern, followed by +01:00 at the end of the string (in my case the time zone is +1). Then use this string as the argument for the date constructor.
// desired format: 2001-02-04T08:16:32+01:00
dateAndTime = year+"-"+month+"-"+day+"T"+hour+":"+minutes+":00+01:00";
var date = new Date(dateAndTime );
Using luxon library:
import { DateTime } from "luxon";
// Convert function:
const convertTz = (datetime, fromTz, toTz, format='yyyy-MM-dd HH:mm:ss') => {
return DateTime.fromFormat(datetime, format, { zone: fromTz }).setZone(toTz).toFormat(format);
}
// Use it like this:
console.log(convertTz('2021-10-03 19:00:00', 'Europe/Lisbon', 'America/New_York'));
You can also use
https://www.npmjs.com/package/ctoc_timezone
It has got much simple implementation and format customisation.
Changing format in toTimeZone:
CtoC.toTimeZone(new Date(),"EST","Do MMM YYYY hh:mm:ss #{EST}");
Output :
28th Feb 2013 19:00:00 EST
You can explore multiple functionalities in the doc.
You can use Intl.DateTimeFormat to specify timezone as an option and it would convert the date or time to your desired timezone.
let timezone = "Asia/Jakarta";
let date = new Date("2012/04/10 10:10:30 +0000");
let formattedDate = new Intl.DateTimeFormat("en-US", { dateStyle: "long" , timeStyle: "short", timeZone: timezone}).format(date);
You can try this also for convert date timezone to India:
var indianTimeZoneVal = new Date().toLocaleString('en-US', {timeZone: 'Asia/Kolkata'});
var indainDateObj = new Date(indianTimeZoneVal);
indainDateObj.setHours(indainDateObj.getHours() + 5);
indainDateObj.setMinutes(indainDateObj.getMinutes() + 30);
console.log(indainDateObj);
I recently did this in Typescript :
// fromTimezone example : Europe/Paris, toTimezone example: Europe/London
private calcTime( fromTimezone: string, toTimezone: string, dateFromTimezone: Date ): Date {
const dateToGetOffset = new Date( 2018, 5, 1, 12 );
const fromTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: fromTimezone, hour12: false } );
const toTimeString = dateToGetOffset.toLocaleTimeString( "en-UK", { timeZone: toTimezone, hour12: false } );
const fromTimeHours: number = parseInt( fromTimeString.substr( 0, 2 ), 10 );
const toTimeHours: number = parseInt( toTimeString.substr( 0, 2 ), 10 );
const offset: number = fromTimeHours - toTimeHours;
// convert to msec
// add local time zone offset
// get UTC time in msec
const dateFromTimezoneUTC = Date.UTC( dateFromTimezone.getUTCFullYear(),
dateFromTimezone.getUTCMonth(),
dateFromTimezone.getUTCDate(),
dateFromTimezone.getUTCHours(),
dateFromTimezone.getUTCMinutes(),
dateFromTimezone.getUTCSeconds(),
);
// create new Date object for different city
// using supplied offset
const dateUTC = new Date( dateFromTimezoneUTC + ( 3600000 * offset ) );
// return time as a string
return dateUTC;
}
I Use "en-UK" format because it is a simple one. Could have been "en-US" or whatever works.
If first argument is your locale timezone and seconde is your target timezone it returns a Date object with the correct offset.
Having looked around a lot including links from this page i found this great article, using moment timezone:
https://www.webniraj.com/2016/11/23/javascript-using-moment-js-to-display-dates-times-in-users-timezone/
To summarise it:
Get the user's timezone
var tz = moment.tz.guess();
console.info('Timezone: ' + tz);
Returns eg: Timezone: Europe/London
Set the default user timezone
moment.tz.setDefault(tz);
Set custom timezone
moment.tz.setDefault('America/Los_Angeles');
Convert date / time to local timezone, assumes original date/time is in UTC
moment.utc('2016-12-25 07:00').tz(tz).format('ddd, Do MMMM YYYY, h:mma');
Returns: Sun, 25th December 2016, 7:00am
Convert date/time to LA Time
moment.utc('2016-12-25 07:00').tz('America/Los_Angeles').format('ddd, Do MMMM YYYY, h:mma');
Returns: Sat, 24th December 2016, 11:00pm
Convert from LA time to London
moment.tz('2016-12-25 07:00', 'America/Los_Angeles').tz('Europe/London').format( 'ddd, Do MMMM YYYY, h:mma' );
Returns: Sun, 25th December 2016, 3:00pm
Provide the desired time zone, for example "Asia/Tehran" to change the current time to that timezone. I used "Asia/Seoul".
You can use the following codes. change the style if you need to do so.
please keep in mind that if you want to have h:m:s format instead of HH:MM:SS, you'll have to remove "function kcwcheckT(i)".
function kcwcheckT(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function kcwt() {
var d = new Date().toLocaleString("en-US", {timeZone: "Asia/Seoul"});
d = new Date(d);
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
h = kcwcheckT(h);
m = kcwcheckT(m);
s = kcwcheckT(s);
document.getElementById("kcwcurtime").innerHTML = h + ":" + m + ":" + s;
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("kcwcurday").innerHTML = days[d.getDay()]
}
kcwt();
window.setInterval(kcwt, 1000);
#import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
.kcwsource {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwsource p {font-family: 'Nunito', sans-serif;}
.CurTbx {color:#040505;cursor: pointer;display:block;width: 100%;border: none;border-radius:5px;text-align:center;padding: 5px 10px 5px 10px;}
.kcwcstyle {font-family: 'Nunito', sans-serif; font-size: 22px;display: inline-block;}
.kcwcurstinf {font-family: 'Nunito', sans-serif; font-size: 18px;display: inline-block;margin: 0;}
.kcwcurday {margin: 0;}
.kcwcurst {margin: 0 10px 0 5px;}
/*Using the css below you can make your style responsive!*/
#media (max-width: 600px){
.kcwcstyle {font-size: 14px;}
.kcwcurstinf {font-size: 12px;}
}
<div class="kcwsource"><p>This Pen was originally developed for KOCOWAFA.com</p></div>
<div class="CurTbx"><p class="kcwcurst kcwcstyle" id="kcwcurday"></p><p class="kcwcurst kcwcstyle" id="kcwcurtime"></p><p class="kcwcurstinf">(Seoul, Korea)</p></div>
Do it as easy:
const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
console.log(timeZone);
var d = new Date();
console.log(d.toLocaleString('en-US', { timeZone }));
I don't know an easy method to convert a date object to any time zone, but if you want to convert it to the local time zone, you can just convert it with Date.prototype.getTime() to the corresponding number of milliseconds, and back again.
let date0 = new Date('2016-05-24T13:07:20');
let date1 = new Date(date0.getTime());
console.log(`${date0}\n${date1}`);
For example, date.getHours() will now return 15 instead of 13 if you are, like me, in Austria (and it's summer).
I've read that the various datetime functions may exhibit non-standard behaviour in some browsers, so test this first. I can confirm that it works in Chrome.
People familiar with the java 8 java.time package, or joda-time will probably love the new kid on the block: the js-joda library.
Install
npm install js-joda js-joda-timezone --save
Example
<script src="node_modules/js-joda/dist/js-joda.js"></script>
<script src="node_modules/js-joda-timezone/dist/js-joda-timezone.js"></script>
<script>
var dateStr = '2012/04/10 10:10:30 +0000';
JSJoda.use(JSJodaTimezone);
var j = JSJoda;
// https://js-joda.github.io/js-joda/esdoc/class/src/format/DateTimeFormatter.js~DateTimeFormatter.html#static-method-of-pattern
var zonedDateTime = j.ZonedDateTime.parse(dateStr, j.DateTimeFormatter.ofPattern('yyyy/MM/dd HH:mm:ss xx'));
var adjustedZonedDateTime = zonedDateTime.withZoneSameInstant(j.ZoneId.of('America/New_York'));
console.log(zonedDateTime.toString(), '=>', adjustedZonedDateTime.toString());
// 2012-04-10T10:10:30Z => 2012-04-10T06:10:30-04:00[America/New_York]
</script>
In true java nature, it's pretty verbose lol. But, being a ported java library, especially considering they ported 1800'ish test cases, it also probably works superbly accurately.
Chrono manipulation is hard. That's why many other libraries are buggy in edge cases. Moment.js seems to get timezones right, but the other js libs I've seen, including timezone-js, don't seem trustworthy.
I was having trouble using Moment Timezone. I am adding this answer just so if somebody else faces the same issue. So I have a date string 2018-06-14 13:51:00 coming from my API. I know that this is stored in UTC but the string doesn't speak for itself.
I let moment timezone know, what timezone this date is from by doing:
let uTCDatetime = momentTz.tz("2018-06-14 13:51:00", "UTC").format();
// If your datetime is from any other timezone then add that instead of "UTC"
// this actually makes the date as : 2018-06-14T13:51:00Z
Now I would like to convert it to a specific timezone by doing:
let dateInMyTimeZone = momentTz.tz(uTCDatetime, "Asia/Kolkata").format("YYYY-MM-DD HH:mm:ss");
// now this results into: 2018-06-14 19:21:00, which is the corresponding date in my timezone.
Just set your desire country timezone and You can easily show in html it update using SetInteval() function after every one minut. function formatAMPM() manage 12 hour format and AM/PM time display.
$(document).ready(function(){
var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
pakTime = new Date(pakTime);
var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
libyaTime = new Date(libyaTime);
document.getElementById("pak").innerHTML = "PAK "+formatAMPM(pakTime);
document.getElementById("ly").innerHTML = "LY " +formatAMPM(libyaTime);
setInterval(function(today) {
var pakTime = new Date().toLocaleString("en-US", {timeZone: "Asia/Karachi"});
pakTime = new Date(pakTime);
var libyaTime = new Date().toLocaleString("en-US", {timeZone: "Africa/Tripoli"});
libyaTime = new Date(libyaTime);
document.getElementById("pak").innerHTML = "PAK "+formatAMPM(pakTime);
document.getElementById("ly").innerHTML = "LY " +formatAMPM(libyaTime);
},10000);
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
});
there is server issue pick gmt+0000 standard time zone you can change it by using library moment-timezone in javascript
const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"
A bit redundant with all these answers, but this worked for me for getting the current Date object with a specific hourly offset.
function hourToMs(hour)
{
return hour * 60 * 1000 * 60;
}
function minToMs(min)
{
return min * 60 * 1000;
}
function getCurrentDateByOffset(offset)
{
// Get the current timezone in milliseconds to reset back to GMT aka +0
let timezoneOffset = minToMs((new Date()).getTimezoneOffset());
// get the desired offset in milliseconds, invert the value because javascript is dum
let desiredOffset = hourToMs(offset * -1);
return new Date(Date.now() + timezoneOffset - desiredOffset);
}
// -6 hours is central timezone
console.log("The time is: " + getCurrentDateByOffset(-6));
There is an npm module called timezones.json you can use for this. It basically consists of a json file with objects containing information on daylight savings and offset.
For asia/jakarta, it would be able to return this object:
{
"value": "SE Asia Standard Time",
"abbr": "SAST",
"offset": 7,
"isdst": false,
"text": "(UTC+07:00) Bangkok, Hanoi, Jakarta",
"utc": [
"Antarctica/Davis",
"Asia/Bangkok",
"Asia/Hovd",
"Asia/Jakarta",
"Asia/Phnom_Penh",
"Asia/Pontianak",
"Asia/Saigon",
"Asia/Vientiane",
"Etc/GMT-7",
"Indian/Christmas"
]
}
You can find it here:
https://github.com/dmfilipenko/timezones.json
https://www.npmjs.com/package/timezones.json
hope it's useful
This is worked for me in React Native Application.
import moment from 'moment-timezone'
function convertTZ(date, tzString) {
const formatedDate = moment(date).tz(tzString).format()
return formatedDate
}
export {convertTZ}
This should work for everyone. You can test out different time zones by changing the time manually on your machine. This function will adapt accordingly.
function getCurrentTime() {
const d = new Date() //2022-07-22T16:27:21.322Z
const t = d.getTime(); //d in milliseconds 1658507241322
const offset = -d.getTimezoneOffset()/60 //current offset in hours -4
const curretMilli = t + (offset * 3600000) //cuuret local time milliseconds need to convert offset to milliseconds
return new Date(curretMilli) //converts current local time in milliseconds to a Date //2022-07-22T12:27:21.322Z
}
This is UTC date; converting UTC to IST timezone;
let sampleArray = [
{
date: "2022-12-22T19:16:26.803"
},
{
date: "2022-12-22T19:16:26.77"
},
{
date: "2022-12-22T19:16:26.737"
},
{
date: "2022-12-22T19:16:26.72"
}
];
// Get all the results whose boolresult is 'true'
// solution 1
sampleArray.map((element) => {
let utcDate = new Date(element.date).getTime();
let dateIST = new Date(utcDate);
dateIST.setHours(dateIST.getHours() + 5);
dateIST.setMinutes(dateIST.getMinutes() + 30);
element.date = dateIST;
});
console.log("Result ==>>", sampleArray);
// solution 2
sampleArray.map((element) => {
element.date = new Date(element.date).toLocaleString("en-US", {
timeZone: "Asia/Kolkata"
});
});
console.log("Result 2==>>", sampleArray);
I want to set GMT+5:30 as my timezone in jquery countdown.
Start Time for countdown is 'Thu May 20 16:00:00 IST 2010'
End Time is 'Thu May 20 17:00:00 IST 2010' as value.
+330 is my timezone given in minutes.
But my countdown starts from 00:35:00.
I would have expected the countdown to start from 01:00:00
Not sure why this is discrepancy is there.
<script type="text/javascript">
$(function () {
var endTime = '#{myBean.getCountDownDate()}';
$('#defaultCountdown').countdown({
until: endTime, format: 'HMS',
timezone: +330,
compact: true, description: '#{myBean.getCountDownDate()}'});
});
</script>
When using the until parameter the countdown plugin counts down until that time.
This will run for one hour using the correct offset.
$('#countdown').countdown({
until: $.countdown.UTCDate(+330, 2010, 6-1, 20, 17),
format: 'HMS',
compact: true
});
Since 2010:06:20:17 has already passed it will display 00:00:00.
I would bet the reason you got 00:35:00 in your countdown is that you were looking at it around 2010:06:20:16:25.
What happens when you change your End Time format to 'Thu, 20 May 2010 17:00:00 IST'?
-edit-
It looks like you're not supposed to pass the date value to until as a String. You can pass in a Date to specify the exact date/time, but a string is only supposed to be used as a time offset, which is why you always get the same amount of time remaining when you refresh.
I couldn't get Date to convert the string with the 'IST' time zone, so I ended up using 'GMT+05:30'. I also put the timezone offset in terms of hours instead of minutes.
<script type="text/javascript">
$(function () {
var endTime = "Tue, 29 Jun 2010 12:00:00 GMT+0530";
$('#defaultCountdown').countdown({
until: new Date(endTime), format: 'HMS',
timezone: +5.5,
compact: true, description: endTime.toString()});
});
</script>
to set timer with eastern timezone
<script>
setInterval(function(){
var timeZone = "America/New_York";
var TimerEndDate = "Nov 25 2022";
var endHour = 23;
var endMinute = 59;
var endSeconds = 59;
//for starting time for timer
//bydefault set to america current time
var nowDate = new Date();
var nowTimeZone = convertTZ(nowDate, timeZone);
var now = new Date(nowTimeZone.getFullYear(),nowTimeZone.getMonth(),nowTimeZone.getDate());
now.setHours(nowTimeZone.getHours(), nowTimeZone.getMinutes(), nowTimeZone.getSeconds());
var endDate = new Date(TimerEndDate+" "+endHour+":"+endMinute+":"+endSeconds);
var endDateTime = convertTZ(endDate, timeZone);
var future = new Date(endDateTime.getFullYear(),endDateTime.getMonth(),endDateTime.getDate());
future.setHours(endHour, endMinute, endSeconds);
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
</script>
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>