How to convert Time to UTC given its timezone? [duplicate] - javascript

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);

Related

Converting date JavaScript

I'm currently populating a table with data from a soap web service, the date comes as a string (example 44250). I created a function to format it into a yyyy/mm/dd format.
Outside the loop I have this function:
Date.prototype.addDays = function (days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
};
Inside the loop I have:
else if (detailsItem == details[i].children[1].innerHTML) {
const dbDays = days[i].innerHTML;
const daysInt = parseInt(dbDays, 0);
const newDate = firstDate.addDays(daysInt);
// Format the date to a readable value
const partsDate = {
date: newDate.getDate(),
month: newDate.getMonth() + 1,
year: newDate.getYear() + 1900,
};
finalDate = `${partsDate.date}/${partsDate.month}/${partsDate.year}`;
const td = document.createElement("td");
td.textContent = finalDate;
tr.appendChild(td);
}
the else if is just checking when to add the date to the table while populating it.
I now need to send a request to the service using the date again but in the previous format, but the date has to be in the same row as the button click, the service only accepts the string format of the date, I'm currently stuck and unsure on how to format it back.
This is the button click function which has to then format the date back to a format such as 44250.
btn.onclick = function () {
// Loops through the table to find the slot and date when clicking the button on the same row
var tableRow = document.getElementById("booking-table"),
rIndex;
for (var i = 0; i < tableRow.rows.length; i++) {
tableRow.rows[i].onclick = function () {
rIndex = this.rowIndex;
bookingDay = this.cells[1].innerHTML;
bookingSlot = this.cells[2].innerHTML;
console.log(bookingSlot, bookingDay);
};
}
Any help on how to accomplish this would be appreciated.
The value "44250" looks like the number of days since 31 Dec 1899 (the epoch), which means a value of "1" converts to 1 Jan 1900. If that's correct, you can create a Date from it using:
let dbDays = '44250';
let date = new Date(1900, 0, dbDays); // 24 Feb 2021
In this algorithm, 1 is 1 Jan 1900 and 0 is 31 Dec 1899.
You can convert it back to an epoch offset using the reverse algorithm:
let dbDays = Math.round((date.getTime() - new Date(1899, 11, 31) / 8.64e7);
Which gets the difference in ms since the date and the epoch, then divides by ms in one day and rounds it to account for possible daylight saving effects where days aren't exactly 24 hours long. This method only works for whole days, it doesn't work for partial days.
The algorithm might be out by a day if 1 Jan 1900 should be 0 rather than 1, just adjust the base dates used in the functions.
Simple functions to go from dbDate to Date instance and back are:
// Convert epoch days to Date
function toDate(dbDays) {
return new Date(1900, 0, +dbDays);
}
// Convert Date to epoch days
function toDBDays(date) {
return Math.round((date - new Date(1899,11,31)) / 8.64e7);
}
// Format date as dd/mm/yyyy
function formatDate(d) {
let z = n => ('0'+n).slice(-2);
return z(d.getDate()) + '/' + z(d.getMonth()+1) + '/' + d.getFullYear();
}
// Parse date in d/m/y format, any non-digit separator
function parseDate(s) {
let [d,m,y] = s.split(/\D/);
return new Date(y, m - 1, d)
}
// Example
let dbDays = '44250';
let d1 = toDate(dbDays); // 24 Feb 2021
let ts = formatDate(d1); // 24/02/2021
let d2 = parseDate(ts); // date object
console.log(dbDays + ' to Date: ' + ts);
console.log(ts + ' to dbDays: ' + toDBDays(d2));
PS Given the epoch won't change, instead of creating a date for 31 Dec 1899 and getting its time value, the constant -2209111200000 can be used.
Notes on your code:
const daysInt = parseInt(dbDays, 0);
The second argument to parseInt is a radix or base to use for conversion to number. The value 0 is replaced with 10 (the default radix), so the above is equivalent to:
const daysInt = parseInt(dbDays, 10);
Then there is:
const partsDate = {
date: newDate.getDate(),
month: newDate.getMonth() + 1,
year: newDate.getYear() + 1900,
};
The getYear method returns a 2 digit year, it's not recommended and is supported mostly for historic reasons, use getFullYear instead.
Using an object for temporary storage is not really optimal, just use variables:
let date = newDate.getDate(),
month = newDate.getMonth() + 1,
year = newDate.getFullYear();
Note that this doesn't pad single digit days or months with leading zeros so will produce timestamps like 1/1/2021 instead of 01/01/2021.
You can use momentjs to convert the date easier: https://momentjs.com/ ,
about the use of the date after you pass that value to the html, can you store that value on some global variable,sesion or localstorage? and then use it later? to call again the soap service? i'm asumming your working on a web page, cause your using html :)

How to compare dates across timezones in JavaScript?

I'm trying to compare given date with current date, It is working fine for Indian timezone but other time zones getting one day off. I have went through similar type of issues and there suggestions are like convert UTC string. After converting UTC string getting correct date while console but when comparing not get correct result.
Here my given date in the format like 'YYYY-MM-DD'.
The initial comparison was like below, and this will work fine for Indian timezone.
const datestring = '2019-05-06';
const q = new Date();
const m = q.getMonth();
const d = q.getDate();
const y = q.getFullYear();
const currentDate = new Date(y, m, d);
const givenDate = new Date(datestring);
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}
}
The above one will work fine for Indian time zone and for some other time zone apart from Indian time zone, it is giving one day less.
But after converting to UTC like:
const givenDate = new Date(datestring).toUTCString();
Now this will give correct date but for comparing purpose I have converted both current date also to UTC string, by that time result is not coming as expected. I know there are number of articles existed related to this but not getting proper way so only posting this question.
The difficulty is that new Date() will create a date in YOUR timezone. For me, since I'm SAST (+2 hours), if I say new Date(2019, 4, 6) I will get the UTC datetime 5 May 22:00 2019. This makes it difficult to compare dates, since someone in India who wanted to compare "6 May 2019" will actually get a UTC date 6 May 2019, and that won't equal 5 May 2019.
Instead use Date.UTC(year, month, day) - an epoch time is number of milliseconds since 2970, Jan 1st in UTC.
const today = new Date()
const todayYear = today.getFullYear()
const todayMonth = today.getMonth()
const todayDay = today.getDate()
const todayUtc = Date.UTC(todayYear, todayMonth, todayDay)
const dateString = 'yyyy-mm-dd'
const dateArr = dateString.split('-')
const dateUtc = Date.UTC(dateArr[0], dateArr[1], dateArr[2])
if (todayUtc === dateUtc) {
// ...
}
You can use getTime to do the comparaison:
// ...
const currentDate = new Date(y, m, d).getTime();
const givenDate = new Date(datestring).getTime();
if (currentDate <= givenDate) {
return null;
} else {
return {
'currentDateChecker': true
};
}

Converting a time string to a time value in javascript

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)

Convert UTC datetime to local datetime

I tried many times to convert utc datetime to local datetime,and I have failed. My utc datetime format is
Fri Mar 8 23:12:27 UTC+0200 2013
Also my JavaScript code is
var time = Date(param_time);//param_time is /Date(1362866006646)/
And then time is being Sun Mar 10 00:21:54 UTC+0200 2013 I need to datetime as 2008-01-28T20:24:17Z because I will convert local datetime to pretty datetime.
http://ejohn.org/files/pretty.js
How can I do this ? I looked at many questions on stackoverflow but no one does it work. Thank you.
In order to format your Date correctly use toISOString():
var time = param_time.toISOString();
Note that param_time needs to be a valid Date object.
References
MDN: Date (sections: Syntax, Example: ISO 8601 formatted dates)
I rarely use javascript and all this date time conversion are mystery to me as well, javascript is a client side technology and all this "UTC" phrases means nothing (at least to me), as all the kind of getUTC...()/setUTC...() functions works in local time, the same is goes for all Date.to...String() functions, even the new Date() (that due to the docs) s'd be initialized in UTC, also give a local time.
However, if you have a (correct) date in UTC and wish to convert it to current (client side) local time, then you need getTimezoneOffset(), or shortly:
function UTCToLocalTime(d) {
var timeOffset = -((new Date()).getTimezoneOffset()/60);
d.setHours(d.getHours() + timeOffset);
return d;
}
var time = new Date(Date.parse('Fri Mar 8 23:12:27 UTC+0200 2013'));
alert(UTCToLocalTime(time)); // Sat Mar 9 01:12:27 UTC+0200 2013
//p.s. or...
function UTCToLocalTime2(d)
{
return new Date(d.toString().replace(/UTC.*/g,"") + d.getYear());
}
var timezone = "UTC+01:30";
var start = new Date();
if(timezone != "UTC"){
timezone = timezone.replace(/UTC/g,"");
znak = timezone.charAt(0);
timezone = timezone.replace(/[+|-]/g,"");
timezone = timezone.split(":");
//var start = new Date(start.toString() + " " + timezone);e.
//alert(start.toString());
if(znak == "+") start = new Date(start.getTime() + (timezone[0]*60*60000 + timezone[1] * 60000) );
if(znak == "-") start = new Date(start.getTime() - (timezone[0]*60*60000 + timezone[1] * 60000) );
}
var hours = start.getUTCHours();
var minutes = start.getUTCMinutes();
var seconds = start.getUTCSeconds();
var day = 10;
var month = 04;
var year = 2015;
var dateUtc = Date.UTC(year, month - 1, day + 1, 0, 0, 0);
> 1428710400000
var toDate = new Date(dateUtc);
> Fri Apr 10 2015 21:00:00 GMT-0300 (Hora oficial do Brasil)

Create a Date with a set timezone without using a string representation

I have a web page with three dropdowns for day, month and year. If I use the JavaScript Date constructor that takes numbers, then I get a Date object for my current timezone:
new Date(xiYear, xiMonth, xiDate)
Give the correct date, but it thinks that date is GMT+01:00 due to daylight savings time.
The problem here is that I then pass this Date to an Ajax method and when the date is deserialised on the server it has been converted to GMT and so lost an hour which moves the day back by one.
Now I could just pass the day, month, and year individually into the Ajax method, but it seems that there ought to be a better way.
The accepted answer pointed me in the right direction, however just using setUTCHours() by itself changed:
Apr 5th 00:00 GMT+01:00
to
Apr 4th 23:00 GMT+01:00
I then also had to set the UTC date, month and year to end up with
Apr 5th 01:00 GMT+01:00
which is what I wanted.
using .setUTCHours() it would be possible to actually set dates in UTC-time, which would allow you to use UTC-times throughout the system.
You cannot set it using UTC in the constructor though, unless you specify a date-string.
Using new Date(Date.UTC(year, month, day, hour, minute, second)) you can create a Date-object from a specific UTC time.
Simply Set the Time Zone and Get Back According
new Date().toLocaleString("en-US", {timeZone: "America/New_York"})
Other Time-zones are as Following
var world_timezones =
[
'Europe/Andorra',
'Asia/Dubai',
'Asia/Kabul',
'Europe/Tirane',
'Asia/Yerevan',
'Antarctica/Casey',
'Antarctica/Davis',
'Antarctica/DumontDUrville',
'Antarctica/Mawson',
'Antarctica/Palmer',
'Antarctica/Rothera',
'Antarctica/Syowa',
'Antarctica/Troll',
'Antarctica/Vostok',
'America/Argentina/Buenos_Aires',
'America/Argentina/Cordoba',
'America/Argentina/Salta',
'America/Argentina/Jujuy',
'America/Argentina/Tucuman',
'America/Argentina/Catamarca',
'America/Argentina/La_Rioja',
'America/Argentina/San_Juan',
'America/Argentina/Mendoza',
'America/Argentina/San_Luis',
'America/Argentina/Rio_Gallegos',
'America/Argentina/Ushuaia',
'Pacific/Pago_Pago',
'Europe/Vienna',
'Australia/Lord_Howe',
'Antarctica/Macquarie',
'Australia/Hobart',
'Australia/Currie',
'Australia/Melbourne',
'Australia/Sydney',
'Australia/Broken_Hill',
'Australia/Brisbane',
'Australia/Lindeman',
'Australia/Adelaide',
'Australia/Darwin',
'Australia/Perth',
'Australia/Eucla',
'Asia/Baku',
'America/Barbados',
'Asia/Dhaka',
'Europe/Brussels',
'Europe/Sofia',
'Atlantic/Bermuda',
'Asia/Brunei',
'America/La_Paz',
'America/Noronha',
'America/Belem',
'America/Fortaleza',
'America/Recife',
'America/Araguaina',
'America/Maceio',
'America/Bahia',
'America/Sao_Paulo',
'America/Campo_Grande',
'America/Cuiaba',
'America/Santarem',
'America/Porto_Velho',
'America/Boa_Vista',
'America/Manaus',
'America/Eirunepe',
'America/Rio_Branco',
'America/Nassau',
'Asia/Thimphu',
'Europe/Minsk',
'America/Belize',
'America/St_Johns',
'America/Halifax',
'America/Glace_Bay',
'America/Moncton',
'America/Goose_Bay',
'America/Blanc-Sablon',
'America/Toronto',
'America/Nipigon',
'America/Thunder_Bay',
'America/Iqaluit',
'America/Pangnirtung',
'America/Atikokan',
'America/Winnipeg',
'America/Rainy_River',
'America/Resolute',
'America/Rankin_Inlet',
'America/Regina',
'America/Swift_Current',
'America/Edmonton',
'America/Cambridge_Bay',
'America/Yellowknife',
'America/Inuvik',
'America/Creston',
'America/Dawson_Creek',
'America/Fort_Nelson',
'America/Vancouver',
'America/Whitehorse',
'America/Dawson',
'Indian/Cocos',
'Europe/Zurich',
'Africa/Abidjan',
'Pacific/Rarotonga',
'America/Santiago',
'America/Punta_Arenas',
'Pacific/Easter',
'Asia/Shanghai',
'Asia/Urumqi',
'America/Bogota',
'America/Costa_Rica',
'America/Havana',
'Atlantic/Cape_Verde',
'America/Curacao',
'Indian/Christmas',
'Asia/Nicosia',
'Asia/Famagusta',
'Europe/Prague',
'Europe/Berlin',
'Europe/Copenhagen',
'America/Santo_Domingo',
'Africa/Algiers',
'America/Guayaquil',
'Pacific/Galapagos',
'Europe/Tallinn',
'Africa/Cairo',
'Africa/El_Aaiun',
'Europe/Madrid',
'Africa/Ceuta',
'Atlantic/Canary',
'Europe/Helsinki',
'Pacific/Fiji',
'Atlantic/Stanley',
'Pacific/Chuuk',
'Pacific/Pohnpei',
'Pacific/Kosrae',
'Atlantic/Faroe',
'Europe/Paris',
'Europe/London',
'Asia/Tbilisi',
'America/Cayenne',
'Africa/Accra',
'Europe/Gibraltar',
'America/Godthab',
'America/Danmarkshavn',
'America/Scoresbysund',
'America/Thule',
'Europe/Athens',
'Atlantic/South_Georgia',
'America/Guatemala',
'Pacific/Guam',
'Africa/Bissau',
'America/Guyana',
'Asia/Hong_Kong',
'America/Tegucigalpa',
'America/Port-au-Prince',
'Europe/Budapest',
'Asia/Jakarta',
'Asia/Pontianak',
'Asia/Makassar',
'Asia/Jayapura',
'Europe/Dublin',
'Asia/Jerusalem',
'Asia/Kolkata',
'Indian/Chagos',
'Asia/Baghdad',
'Asia/Tehran',
'Atlantic/Reykjavik',
'Europe/Rome',
'America/Jamaica',
'Asia/Amman',
'Asia/Tokyo',
'Africa/Nairobi',
'Asia/Bishkek',
'Pacific/Tarawa',
'Pacific/Enderbury',
'Pacific/Kiritimati',
'Asia/Pyongyang',
'Asia/Seoul',
'Asia/Almaty',
'Asia/Qyzylorda',
'Asia/Qostanay',
'Asia/Aqtobe',
'Asia/Aqtau',
'Asia/Atyrau',
'Asia/Oral',
'Asia/Beirut',
'Asia/Colombo',
'Africa/Monrovia',
'Europe/Vilnius',
'Europe/Luxembourg',
'Europe/Riga',
'Africa/Tripoli',
'Africa/Casablanca',
'Europe/Monaco',
'Europe/Chisinau',
'Pacific/Majuro',
'Pacific/Kwajalein',
'Asia/Yangon',
'Asia/Ulaanbaatar',
'Asia/Hovd',
'Asia/Choibalsan',
'Asia/Macau',
'America/Martinique',
'Europe/Malta',
'Indian/Mauritius',
'Indian/Maldives',
'America/Mexico_City',
'America/Cancun',
'America/Merida',
'America/Monterrey',
'America/Matamoros',
'America/Mazatlan',
'America/Chihuahua',
'America/Ojinaga',
'America/Hermosillo',
'America/Tijuana',
'America/Bahia_Banderas',
'Asia/Kuala_Lumpur',
'Asia/Kuching',
'Africa/Maputo',
'Africa/Windhoek',
'Pacific/Noumea',
'Pacific/Norfolk',
'Africa/Lagos',
'America/Managua',
'Europe/Amsterdam',
'Europe/Oslo',
'Asia/Kathmandu',
'Pacific/Nauru',
'Pacific/Niue',
'Pacific/Auckland',
'Pacific/Chatham',
'America/Panama',
'America/Lima',
'Pacific/Tahiti',
'Pacific/Marquesas',
'Pacific/Gambier',
'Pacific/Port_Moresby',
'Pacific/Bougainville',
'Asia/Manila',
'Asia/Karachi',
'Europe/Warsaw',
'America/Miquelon',
'Pacific/Pitcairn',
'America/Puerto_Rico',
'Asia/Gaza',
'Asia/Hebron',
'Europe/Lisbon',
'Atlantic/Madeira',
'Atlantic/Azores',
'Pacific/Palau',
'America/Asuncion',
'Asia/Qatar',
'Indian/Reunion',
'Europe/Bucharest',
'Europe/Belgrade',
'Europe/Kaliningrad',
'Europe/Moscow',
'Europe/Simferopol',
'Europe/Kirov',
'Europe/Astrakhan',
'Europe/Volgograd',
'Europe/Saratov',
'Europe/Ulyanovsk',
'Europe/Samara',
'Asia/Yekaterinburg',
'Asia/Omsk',
'Asia/Novosibirsk',
'Asia/Barnaul',
'Asia/Tomsk',
'Asia/Novokuznetsk',
'Asia/Krasnoyarsk',
'Asia/Irkutsk',
'Asia/Chita',
'Asia/Yakutsk',
'Asia/Khandyga',
'Asia/Vladivostok',
'Asia/Ust-Nera',
'Asia/Magadan',
'Asia/Sakhalin',
'Asia/Srednekolymsk',
'Asia/Kamchatka',
'Asia/Anadyr',
'Asia/Riyadh',
'Pacific/Guadalcanal',
'Indian/Mahe',
'Africa/Khartoum',
'Europe/Stockholm',
'Asia/Singapore',
'America/Paramaribo',
'Africa/Juba',
'Africa/Sao_Tome',
'America/El_Salvador',
'Asia/Damascus',
'America/Grand_Turk',
'Africa/Ndjamena',
'Indian/Kerguelen',
'Asia/Bangkok',
'Asia/Dushanbe',
'Pacific/Fakaofo',
'Asia/Dili',
'Asia/Ashgabat',
'Africa/Tunis',
'Pacific/Tongatapu',
'Europe/Istanbul',
'America/Port_of_Spain',
'Pacific/Funafuti',
'Asia/Taipei',
'Europe/Kiev',
'Europe/Uzhgorod',
'Europe/Zaporozhye',
'Pacific/Wake',
'America/New_York',
'America/Detroit',
'America/Kentucky/Louisville',
'America/Kentucky/Monticello',
'America/Indiana/Indianapolis',
'America/Indiana/Vincennes',
'America/Indiana/Winamac',
'America/Indiana/Marengo',
'America/Indiana/Petersburg',
'America/Indiana/Vevay',
'America/Chicago',
'America/Indiana/Tell_City',
'America/Indiana/Knox',
'America/Menominee',
'America/North_Dakota/Center',
'America/North_Dakota/New_Salem',
'America/North_Dakota/Beulah',
'America/Denver',
'America/Boise',
'America/Phoenix',
'America/Los_Angeles',
'America/Anchorage',
'America/Juneau',
'America/Sitka',
'America/Metlakatla',
'America/Yakutat',
'America/Nome',
'America/Adak',
'Pacific/Honolulu',
'America/Montevideo',
'Asia/Samarkand',
'Asia/Tashkent',
'America/Caracas',
'Asia/Ho_Chi_Minh',
'Pacific/Efate',
'Pacific/Wallis',
'Pacific/Apia',
'Africa/Johannesburg'
];
var d = new Date(xiYear, xiMonth, xiDate);
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
This answer is tailored specifically to the original question, and will not give the answer you necessarily expect. In particular, some people will want to subtract the timezone offset instead of add it. Remember though that the whole point of this solution is to hack javascript's date object for a particular deserialization, not to be correct in all cases.
I believe you need the createDateAsUTC function (please compare with convertDateToUTC)
function createDateAsUTC(date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
function convertDateToUTC(date) {
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}
I don't believe this is possible - there is no ability to set the timezone on a Date object after it is created.
And in a way this makes sense - conceptually (if perhaps not in implementation); per http://en.wikipedia.org/wiki/Unix_timestamp (emphasis mine):
Unix time, or POSIX time, is a system for describing instants in time, defined as the number of seconds elapsed since midnight Coordinated Universal Time (UTC) of Thursday, January 1, 1970.
Once you've constructed one it will represent a certain point in "real" time. The time zone is only relevant when you want to convert that abstract time point into a human-readable string.
Thus it makes sense you would only be able to change the actual time the Date represents in the constructor. Sadly it seems that there is no way to pass in an explicit timezone - and the constructor you are calling (arguably correctly) translates your "local" time variables into GMT when it stores them canonically - so there is no way to use the int, int, int constructor for GMT times.
On the plus side, it's trivial to just use the constructor that takes a String instead. You don't even have to convert the numeric month into a String (on Firefox at least), so I was hoping a naive implementation would work. However, after trying it out it works successfully in Firefox, Chrome, and Opera but fails in Konqueror ("Invalid Date") , Safari ("Invalid Date") and IE ("NaN"). I suppose you'd just have a lookup array to convert the month to a string, like so:
var months = [ '', 'January', 'February', ..., 'December'];
function createGMTDate(xiYear, xiMonth, xiDate) {
return new Date(months[xiMonth] + ' ' + xiDate + ', ' + xiYear + ' 00:00:00 GMT');
}
I know this is old but if it helps you could use moment and moment time zone. If you haven't seen them take a look.
http://momentjs.com/timezone/
http://momentjs.com/
two really handy time manipulation libraries.
If you want to deal with the slightly different, but related, problem of creating a Javascript Date object from year, month, day, ..., including timezone – that is, if you want to parse a string into a Date – then you apparently have to do an infuriatingly complicated dance:
// parseISO8601String : string -> Date
// Parse an ISO-8601 date, including possible timezone,
// into a Javascript Date object.
//
// Test strings: parseISO8601String(x).toISOString()
// "2013-01-31T12:34" -> "2013-01-31T12:34:00.000Z"
// "2013-01-31T12:34:56" -> "2013-01-31T12:34:56.000Z"
// "2013-01-31T12:34:56.78" -> "2013-01-31T12:34:56.780Z"
// "2013-01-31T12:34:56.78+0100" -> "2013-01-31T11:34:56.780Z"
// "2013-01-31T12:34:56.78+0530" -> "2013-01-31T07:04:56.780Z"
// "2013-01-31T12:34:56.78-0330" -> "2013-01-31T16:04:56.780Z"
// "2013-01-31T12:34:56-0330" -> "2013-01-31T16:04:56.000Z"
// "2013-01-31T12:34:56Z" -> "2013-01-31T12:34:56.000Z"
function parseISO8601String(dateString) {
var timebits = /^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(?::([0-9]*)(\.[0-9]*)?)?(?:([+-])([0-9]{2})([0-9]{2}))?/;
var m = timebits.exec(dateString);
var resultDate;
if (m) {
var utcdate = Date.UTC(parseInt(m[1]),
parseInt(m[2])-1, // months are zero-offset (!)
parseInt(m[3]),
parseInt(m[4]), parseInt(m[5]), // hh:mm
(m[6] && parseInt(m[6]) || 0), // optional seconds
(m[7] && parseFloat(m[7])*1000) || 0); // optional fraction
// utcdate is milliseconds since the epoch
if (m[9] && m[10]) {
var offsetMinutes = parseInt(m[9]) * 60 + parseInt(m[10]);
utcdate += (m[8] === '+' ? -1 : +1) * offsetMinutes * 60000;
}
resultDate = new Date(utcdate);
} else {
resultDate = null;
}
return resultDate;
}
That is, you create a 'UTC time' using the date without timezone (so you know what locale it's in, namely the UTC 'locale', and it's not defaulted to the local one), and then manually apply the indicated timezone offset.
Wouldn't it have been nice if someone had actually thought about the Javascript date object for more than, oooh, five minutes....
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000*offset));
offset value base on which location time zone you would like to set
For India offset value +5.5,
New York offset value -4,
London offset value +1
for all location offset Wiki List of UTC time offsets
// My clock 2018-07-25, 00:26:00 (GMT+7)
let date = new Date(); // 2018-07-24:17:26:00 (Look like GMT+0)
const myTimeZone = 7; // my timeZone
// my timeZone = 7h = 7 * 60 * 60 * 1000 (millisecond);
// 2018-07-24:17:26:00 = x (milliseconds)
// finally, time in milliseconds (GMT+7) = x + myTimezone
date.setTime( date.getTime() + myTimeZone * 60 * 60 * 1000 );
// date.toISOString() = 2018-07-25, 00:26:00 (GMT+7)
getTimeZoneOffset is minus for UTC + z.
var d = new Date(xiYear, xiMonth, xiDate);
if(d.getTimezoneOffset() > 0){
d.setTime( d.getTime() + d.getTimezoneOffset()*60*1000 );
}
This may help someone, put UTC at the end of what you pass in to the new constructor
At least in chrome you can say var date = new Date("2014-01-01 11:00:00 UTC")
One line solution
new Date(new Date(1422524805305).getTime() - 330*60*1000)
Instead of 1422524805305, use the timestamp in milliseconds
Instead of 330, use your timezone offset in minutes wrt. GMT (eg India +5:30 is 5*60+30 = 330 minutes)
The easiest way that I have found to get the correct date is using datejs.
http://www.datejs.com/
I get my dates via Ajax in this format as a string: '2016-01-12T00:00:00'
var yourDateString = '2016-01-12T00:00:00';
var yourDate = new Date(yourDateString);
console.log(yourDate);
if (yourDate.getTimezoneOffset() > 0){
yourDate = new Date(yourDateString).addMinutes(yourDate.getTimezoneOffset());
}
console.log(yourDate);
Console will read:
Mon Jan 11 2016 19:00:00 GMT-0500 (Eastern Standard Time)
Tue Jan 12 2016 00:00:00 GMT-0500 (Eastern Standard Time)
https://jsfiddle.net/vp1ena7b/3/
The 'addMinutes' comes from datejs, you could probably do this in pure js on your own, but I already had datejs in my project so I found a way to use it to get the correct dates.
I thought that this might help someone...
This code will return your Date object formatted with the browser timezone.
Date.prototype.timezone = function () {
this.setHours(this.getHours() + (new Date().getTimezoneOffset() / 60));
return this;
}
Edit:
To avoid to pollute the Date API, the above function can be transformed into a utility function. The function takes a Date object, and returns a mutated Date object.
function setTimeZone(date) {
date.setHours(date.getHours() + (new Date().getTimezoneOffset() / 60));
return date;
}
Here is a function that you can use to achieve a date object:
const getUTCDate = (date) => {
const d = new Date(date);
const utcDate = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate());
return utcDate;
}
const string = '1930-08-12T00:00:00.000000Z';
const utcDate = getUTCDate(string);
// returns Tue Aug 12 1930 00:00:00 GMT-0800 (Pacific Daylight Time)
any mileage in
var d = new Date(xiYear, xiMonth, xiDate).toLocaleString();
const date = new Date("2020-12-16 17:45:00 UTC");
Works fine.
I was having a similar problem with a date picker. My research led to a very simple solution, without any extra libraries or hardcoded multipliers.
Key info:
ISO is the Javascript preferred date standard. Assume date utilities will likely return date values in that format.
My date picker displays the date in a localized format: mm/dd/yyyy
However, it returns the date value in the ISO format: yyyy-mm-dd
//Select "08/12/2020" in Date Picker date_input
var input = $('#date_input').val(); //input: 2020-08-12
Date.getTimezoneOffset() returns the offset in minutes.
Examples:
If you use the default returned date value without modifying the string format, the Date might not get set to your timezone. This can lead to unexpected results.
var input = $('#date_input').val(); //input: 2020-08-12
var date = new Date(input); //This get interpreted as an ISO date, already in UTC
//date: Tue Aug 11 2020 20:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 00:00:00 GMT
//date.toLocaleDateString('en-US'): 8/11/2020
Using a different date string format than the ISO standard yyyy-mm-dd applies your timezone to the Date.
var date = new Date("08/12/2020"); //This gets interpreted as local timezone
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
Solution:
To apply your timezone to the format-agnostic Date without doing string manipulation, use Date.getTimezoneOffset() with Minutes. This works with either original date string format (i.e. UTC dates or localized dates). It provides a consistent result which can then be converted accurately to UTC for storage or interacting with other code.
var input = $('#date_input').val();
var date = new Date(input);
date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
//date: Wed Aug 12 2020 00:00:00 GMT-0400 (Eastern Daylight Time)
//date.toUTCString(): Wed, 12 Aug 2020 04:00:00 GMT
//date.toLocaleDateString('en-US'): 8/12/2020
It's actually not very hard at all to do this, but it certainly isn't intuitive to come up with the solution. There are some really convoluted answers here (though also some nice ones). Here's what I came up with to make sure my server timestamps would match my local timestamps, no matter what timezone my deployed server happened to be in.
(CET = Central European Timezone, which just happens to be my personal timezone; you can get the offset of any given timezone and calculate it and even make it an argument if you like, but for my purpose, I just needed to get my dates to all be the single desired consistent timezone.)
const convertDateToCET = function(date) {
date = new Date(date)
// let startTime = date.getTime();
const cetOffset = -120; // this is the number you get from running
// `(new Date()).getTimezoneOffset()` if you're on a machine in CET
const offsetFromCET = (date.getTimezoneOffset() - cetOffset);
const cetMillsecondOffset = ( cetOffset* 60 * 1000);
date = new Date( date.getTime() - cetMillsecondOffset )
// let endTime = date.getTime()
// console.log("updated date from",startTime,"to",endTime)
return date;
},
Using this, you just make a time the way you would expect, e.g.
let myDate = new Date("12-4-2021")
myDate.setHour(14)
myDate.setMinute(30)
// now myDate is 2:30pm, December 4th, 2021, in whatever the timezone the machine of code running happens to be in
myDate = convertDateToCET(myDate)
// now myDate will show up as 2:30pm, Dec 4th, 2021, mapped into your local timezone
// so, if you're in the UK, and one hour behind CET, myDate is now 1:30pm, Dec 4th, 2021
The key here is date.getTimezoneOffset(). If you're actually in CET, that number will be -120, and so it cancels out, making no difference (so CET results in CET out). If you're in the UK, one hour behind CET, that output would be -60, which means -60 + 120 = +60 which results in us changing the input time by one hour, and so on.
It probably makes more sense to convert everything and use everything in UTC for a case like this, but given that all of my input time is in CET and I'd originally developed the system based on how things looked locally on my machine, this utility allowed me to convert the existing code by just making a call to this function in a few key places.
Caution: Make sure not to apply this function call multiple times on the same date, as you'll be reapplying the offset multiple times, throwing it off!
Best Solution I have seen from this came from
http://www.codingforums.com/archive/index.php/t-19663.html
Print Time Function
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)
function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
Full Code Example
<html>
<head>
<script language="javascript" type="text/javascript">
//borrowed from echoecho
//http://www.echoecho.com/ubb/viewthread.php?tid=2362&pid=10482&#pid10482
workDate = new Date()
UTCDate = new Date()
UTCDate.setTime(workDate.getTime()+workDate.getTimezoneOffset()*60000)
function printTime(offset) {
offset++;
tempDate = new Date()
tempDate.setTime(UTCDate.getTime()+3600000*(offset))
timeValue = ((tempDate.getHours()<10) ? ("0"+tempDate.getHours()) : (""+tempDate.getHours()))
timeValue += ((tempDate.getMinutes()<10) ? ("0"+tempDate.getMinutes()) : tempDate.getMinutes())
timeValue += " hrs."
return timeValue
}
var now = new Date()
var seed = now.getTime() % 0xfffffff
var same = rand(12)
</script>
</head>
<body>
Banff, Canada:
<script language="JavaScript">document.write(printTime("-7"))</script>
<br>
Michigan:
<script language="JavaScript">document.write(printTime("-5"))</script>
<br>
Greenwich, England(UTC):
<script language="JavaScript">document.write(printTime("-0"))</script>
<br>
Tokyo, Japan:
<script language="JavaScript">document.write(printTime("+9"))</script>
<br>
Berlin, Germany:
<script language="JavaScript">document.write(printTime("+1"))</script>
</body>
</html>
When I create a date object:
new Date(year, month, day, hour, minute)
I works fine on localhost.
When I deploy to server it breaks, because server is in another timezone.
I can't use getTimezoneOffset(). I need the timezoneOffset of my home - dependent on summertime/wintertime
// add diff minutes between myself (HOME) and server
timezoneHomeOffset (d, tz = 'Europe/Copenhagen') {
const utc = new Date(d.getTime())
const dHome = new Date(d.toLocaleString('en-US', { timeZone: tz }))
const diff = Math.round((utc - dHome) / 60000) // 60*1000 => minutes
d.setMinutes(d.getMinutes() + diff)
return d
}
You can use library to help to change time zone
moment-timezone
var moment = require("moment-timezone");
const today = new Date();
var timeGet = moment(today);
timeGet.tz("Asia/Karachi").format("ha z");
this can change your time zone of your region paste your region area and get real gmt+ resolve issue
For more details visit moment timezone official documentation
This worked fine for different timezones (IST, PST, Mexico, Central America):
let dateUtc: any = new Date(Date.parse(data.details.dateOfBirth));
dateUtc = new Date(dateUtc.getTime() + Math.abs(dateUtc.getTimezoneOffset()*60000));
console.log(dateUtc);
Pain in my brain.
How to get current same date with timezone like on the server with WORDPRESS to js.
var dnow = new Date();
dnow = dnow.getTime() + dnow.getTimezoneOffset()*60*1000 + <?= get_option( 'gmt_offset' ) ?> * 60*60*1000;
First we need to get current date. Then we need to remove user timezone offset. Then we add gmt offset from WordPress option page.
if you want to check the difference in a time between two dates, you can simply check if second timezone is lesser or greater from your first desired timezone and subtract or add a time.
const currTimezone = new Date().getTimezoneOffset(); // your timezone
const newDateTimezone = date.getTimezoneOffset(); // date with unknown timezone
if (currTimezone !== newDateTimezone) {
// and below you are checking if difference should be - or +. It depends on if unknown timezone is lesser or greater than yours
const newTimezone = (currTimezone - newDateTimezone) * (currTimezone > newDateTimezone ? 1 : -1);
date.setTime(date.getTime() + (newTimezone * 60 * 1000));
}
GMT -03:00 Example
new Date(new Date()-3600*1000*3).toISOString(); // 2020-02-27T15:03:26.261Z
Or even
now = new Date().getTime()-3600*1000*3; // 1582818380528
data = new Date(now).toISOString(); // 2020-02-27T15:03:26.261Z
This worked for me. Not sure if it is a good idea though.
var myDate = new Date();
console.log('myDate:', myDate); // myDate: "2018-04-04T01:09:38.112Z"
var offset = '+5'; // e.g. if the timeZone is -5
var MyDateWithOffset = new Date( myDate.toGMTString() + offset );
console.log('MyDateWithOffset:', MyDateWithOffset); // myDateWithOffset: "2018-04-03T20:09:38.000Z"
I used the timezone-js package.
var timezoneJS = require('timezone-js');
var tzdata = require('tzdata');
createDate(dateObj) {
if ( dateObj == null ) {
return null;
}
var nativeTimezoneOffset = new Date().getTimezoneOffset();
var offset = this.getTimeZoneOffset();
// use the native Date object if the timezone matches
if ( offset == -1 * nativeTimezoneOffset ) {
return dateObj;
}
this.loadTimeZones();
// FIXME: it would be better if timezoneJS.Date was an instanceof of Date
// tried jquery $.extend
// added hack to Fiterpickr to look for Dater.getTime instead of "d instanceof Date"
return new timezoneJS.Date(dateObj,this.getTimeZoneName());
},
This is BEST solution
Using:
// TO ALL dates
Date.timezoneOffset(-240) // +4 UTC
// Override offset only for THIS date
new Date().timezoneOffset(-180) // +3 UTC
Code:
Date.prototype.timezoneOffset = new Date().getTimezoneOffset();
Date.setTimezoneOffset = function(timezoneOffset) {
return this.prototype.timezoneOffset = timezoneOffset;
};
Date.getTimezoneOffset = function() {
return this.prototype.timezoneOffset;
};
Date.prototype.setTimezoneOffset = function(timezoneOffset) {
return this.timezoneOffset = timezoneOffset;
};
Date.prototype.getTimezoneOffset = function() {
return this.timezoneOffset;
};
Date.prototype.toString = function() {
var offsetDate, offsetTime;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
return offsetDate.toUTCString();
};
['Milliseconds', 'Seconds', 'Minutes', 'Hours', 'Date', 'Month', 'FullYear', 'Year', 'Day'].forEach((function(_this) {
return function(key) {
Date.prototype["get" + key] = function() {
var offsetDate, offsetTime;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
return offsetDate["getUTC" + key]();
};
return Date.prototype["set" + key] = function(value) {
var offsetDate, offsetTime, time;
offsetTime = this.timezoneOffset * 60 * 1000;
offsetDate = new Date(this.getTime() - offsetTime);
offsetDate["setUTC" + key](value);
time = offsetDate.getTime() + offsetTime;
this.setTime(time);
return time;
};
};
})(this));
Coffee version:
Date.prototype.timezoneOffset = new Date().getTimezoneOffset()
Date.setTimezoneOffset = (timezoneOffset)->
return #prototype.timezoneOffset = timezoneOffset
Date.getTimezoneOffset = ->
return #prototype.timezoneOffset
Date.prototype.setTimezoneOffset = (timezoneOffset)->
return #timezoneOffset = timezoneOffset
Date.prototype.getTimezoneOffset = ->
return #timezoneOffset
Date.prototype.toString = ->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
return offsetDate.toUTCString()
[
'Milliseconds', 'Seconds', 'Minutes', 'Hours',
'Date', 'Month', 'FullYear', 'Year', 'Day'
]
.forEach (key)=>
Date.prototype["get#{key}"] = ->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
return offsetDate["getUTC#{key}"]()
Date.prototype["set#{key}"] = (value)->
offsetTime = #timezoneOffset * 60 * 1000
offsetDate = new Date(#getTime() - offsetTime)
offsetDate["setUTC#{key}"](value)
time = offsetDate.getTime() + offsetTime
#setTime(time)
return time

Categories