Convert inputted time (which is PDT/PST) to local Time - javascript

So far I have created a timezone list for PST, CST, EST, GMT, CEST, IST, AST which works perfectly. But I also want to add an input box that will always be PST and output a local time from it..
i.e. if a user puts in 09:00 then if they live in the UK it will output 17:00
So it basically registers where you are in relation to timezone and adds (or subtracts) from the inputted time. (UK is +8 so input + 8 gives output)
This is my FIDDLE of where I am at right now
https://jsfiddle.net/wayneker/unc7e64f/16/
Although I know this demo is ideal, I know I cannot currently make this (with my current knowledge).
https://greenwichmeantime.com/time/to/pst-local/
I have researched various pages and cannot understand a lot of them. But what I have seen is normally local to PST
window.setInterval(function(){
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(offset) {
//function calcTime(city, offset) {
// create Date object for current location
d = new Date();
//set options
var options = { weekday: "short", year: "numeric", month: "short",
day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" };
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
//return "The local time in " + city + " is " + nd.toLocaleString();
//return nd.toLocaleString();
return nd.toLocaleString("en-US", options);
}
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.dst()) document.getElementById('dst').innerHTML = '';

Here is one way is to convert the PST time back to UTC and then apply the local offset.
function submitfunction() {
var value = document.getElementById("PSTPDT").value;
var parts = value.split(':');
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var offset = now.getTimezoneOffset()
var local = new Date(year, month, date, parts[0], parts[1], parts[2]);
local.setMinutes(local.getMinutes() + 420 - offset);
var result = document.getElementById("result");
result.innerHTML = local
}
See example:
https://jsfiddle.net/p9u5j8dm/

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

Getting the start of the day in a different timezone

I have a Date. It is in the local timezone. I want a new Date that is at the beginning of the dayin a different timezone. Here are some things I do not want:
A Date in UTC equivalent to the first date converted to UTC
A string
Specifically, UTC does not work because getting the start of a day in UTC is not the same as getting the start of the day in a timezone.
So If I have a date in Calcutta and want to get the start of that day in San Francisco, the date in Calcutta and the date in Greenwich might not be the same date. It could be June 15th in Calcutta, June 15th in Greenwich, but June 2nd in San Francisco. So calling setMinutes(0) etc on a date that is set to UTC will not work.
I am also using date-fns (not moment) if that's helpful, but it doesn't seem to be because all dates (including those in date-fns-tz) are returned in either local or UTC time.)
Is this possible in Javascript or am I insane?
Note:
This is not the same as Convert date to another timezone in JavaScript
That is about converting to strings. I do not want strings.
One way is to:
Get the current timezone offset at the required location
Create a date for the required UTC date
Apply the offset from #1
e.g. using the answer at Get Offset of the other Location in Javascript:
function getTimezoneOffset(date, loc) {
let offset;
['en','fr'].some(lang => {
let parts = new Intl.DateTimeFormat(lang, {
minute: 'numeric',
timeZone: loc,
timeZoneName:'short'
}).formatToParts(date);
let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
if (/^(GMT|UTC)/.test(tzName[0].value)) {
offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
return true;
}
});
let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
let [h, m] = offset.substring(1).split(':');
return sign + h.padStart(2, '0') + ':' + (m || '00');
}
// Convert offset string in ±HH:mm to minutes
function offsetToMins(offset) {
let sign = /^-/.test(offset)? -1 : 1;
let [h, m] = offset.match(/\d\d/g);
return sign * (h * 60 + Number(m));
}
// Format date as YYYY-MM-DD at loc
function formatYMD(loc, date) {
let z = n => ('0'+n).slice(-2);
let {year, month, day} = new Intl.DateTimeFormat('en',{timeZone: loc})
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return part;
}, Object.create(null));
return `${year}-${z(month)}-${z(day)}`
}
// Return stat of day for date at loc
function startOfDayAtLoc(loc, date = new Date()) {
let offset = getTimezoneOffset(date, loc);
let offMins = offsetToMins(offset);
let d = new Date(+date);
d.setUTCHours(0, -offMins, 0, 0);
// If date is + or - original date, adjust
let oDateTS = formatYMD(loc, date);
let sodDateTS = formatYMD(loc, d);
if (sodDateTS > oDateTS) {
d.setUTCDate(d.getUTCDate() - 1);
} else if (sodDateTS < oDateTS) {
d.setUTCDate(d.getUTCDate() + 1);
}
return d;
}
// QnD formatter
let f = (loc, d) => d.toLocaleString('en-gb', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour12:false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: loc,
timeZoneName: 'long'
});
// Examples
// 1 June 2020 00:00:00 Z
let d = new Date(Date.UTC(2020, 5, 1));
['America/New_York',
'Asia/Tokyo',
'Pacific/Tongatapu',
'Pacific/Rarotonga'
].forEach(loc => {
let locD = startOfDayAtLoc(loc, d);
console.log(loc + ' ' + getTimezoneOffset(d, loc) +
'\nZulu : ' + locD.toISOString() +
'\nLocal: ' + f(loc, locD));
});
// Dates on different date to UTC date
let laDate = new Date('2022-04-30T18:00:00-07:00');
let la = 'America/Los_Angeles';
console.log(`${la} - ${f(la, laDate)}` +
`\nStart of day: ${f(la, startOfDayAtLoc(la, laDate))}`
);
let chaDate = new Date('2022-05-01T03:00:00+10:00');
let cha = 'Pacific/Chatham';
console.log(`${cha} - ${f(cha, chaDate)}` +
`\nStart of day: ${f(cha, startOfDayAtLoc(cha, chaDate))}`
);
However, I'd suggest you use a library with timezone support as there are many quirks with the Date object and there is a new Temporal object in the works.

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

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

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)

How do I split the date and time into two elements?

I've made an object that displays the date and time live.
I would like to know how I can separate the time part from the date so I can have it in its own HTML element so I can apply different styling to it?
I'm not that advanced with JavaScript, and I find working with the date object very complicated.
LiveDateTime.js
'use strict';
function LiveDateTime(dateEl, options) {
this.dateEl = dateEl;
this.options = options;
this.timestamp;
this.offset;
this.start();
}
LiveDateTime.prototype = {
start: function () {
var now = !this.timestamp ? new Date() : new Date(this.timestamp),
self = this;
(function update() {
self.dateEl.innerHTML = now.toLocaleString(self.options.locale, self.options);
now.setSeconds(now.getSeconds() + 1);
self.timeoutId = setTimeout(update, 1000);
})();
},
stop: function () {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
};
Usage
var liveDateTime = new LiveDateTime(document.getElementById('date'), {
locale: 'FR',
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
//output example: vendredi 13 mars 2015 23:14:12
HTML
<span id="date"></span> - <span id="time"></span>
Use date.toLocaleDateString() for the date part, and date.toLocaleTimeString() for the time part.
You can format your date using Date available methods:
var now = new Date()
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
console.log(date + ' ' + time)
You can use javascript's split() method
var date = liveDateTime.split(" ");
var weekday = date[0];
var day = date[1];
var month = date[2];
var year = date[3];
var time = date[4].split(":");
var hour = time[0];
var minute = time[1];
var second = time[2];
I'm not that advanced with JavaScript, and I find working with the date object very complicated.
Working with date in JS could be indeed complicated and frustrating. But that could be a pleasure by using libraries such momentjs
So as to get the date formatted as you need :
moment().format('dddd Do MMMM YYYY'); // vendredi 13 mars 2015 (with FR locale)
// Friday 13th March 2015 (with EN locale)
And for getting the hour :
moment().format('H:mm:ss'); // 23:36:15
These are just tiny examples of the possibilities of the library.
For other formatting patterns, refer to this table of the documentation
var now = new Date()
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
console.log(date + ' ' + time)

Categories