I have UTC timeZone Date which I want to convert CST or DST based on whether DST is applied in the same city or not.
Since my browser is not based on same city so local time is no use of it.
example: my user is based on India but they will see data for NewYork Date also
I have a server based on NewYork so using SSR I can get date of the server but its always showing in CST how I can change the date into DST?
try this code. it might help you.
let d = new Date()
let utc = d.getTime() + (d.getTimezoneOffset() * 60000)
let today = new Date(utc - (3600000 * 6)) // 6 is for cst timezone. we can change this to get other timezome . this is offset
let dd = today.getDate()
let mm = today.getMonth()+1
let yy = today.getFullYear()
let hh = today.getHours()
let i = today.getMinutes()
let sec = today.getSeconds()
hh = hh.toString().length<2?("0"+hh):hh
mm = mm.toString().length<2?("0"+mm):mm
i = i.toString().length<2?"0"+i:i
sec = sec.toString().length<2?"0"+sec:sec
let timestamp = dd+'/'+mm+'/'+yy+' '+hh+':'+i+':'+sec
console.log('timestamp ',timestamp)
You can use Date.toLocaleString() to convert a UTC date to a specific timezone. This will honour the local DST rules and is native JavaScript code (no libraries required!)
So, if we have a list of UTC dates, we can convert to a specific timezone. I've created a list of UTC dates and timezones and formatted the dates for that timezone and date.
You can select a different display locale of course, for example if you have Indian clients you could use "en-in" or whichever you decide is the best display locale.
You should be able to do any timezone conversion either on the server side or (preferably) on the client side. If you send all dates to the client in UTC format (e.g. YYYY-MM-DDTHH:mm:ssZ) you can convert to the client timezone in the client code.
const displayLocale = "en-us"; // Set this to en-gb, en-in etc..
const uctDateList = [ new Date("2019-06-01T12:00:00Z"), new Date("2019-12-01T12:00:00Z")];
const timeZoneList = ['America/New_York', 'America/Los_Angeles', 'Asia/Kolkata'];
uctDateList.forEach(utcDate => {
console.log("\nServer Time: ", utcDate.toISOString());
timeZoneList.forEach(timeZone => {
console.log(`Time in timezone (${timeZone}):`, utcDate.toLocaleString(displayLocale, { timeZone }));
})
});
Related
I have a list of list of string dates like this: '17/12/2017 19:34'. They are CET dates.
How can I transform it to the user's browser date?
I'm doing this:
const tzGuess = moment.tz.guess()
export const toTimeZone = (time) => {
const format = 'DD/MM/YYYY HH:mm'
return moment(time, format).tz(tzGuess).format(format)
}
console.log(toTimeZone('17/12/2017 19:34', tzGuess))
but how can I say to moment that the date I'm passing at first is a CET one?
Thanks!
You can use moment.tz function for parsing time string using a given timezone (e.g. 'Europe/Madrid').
The issue is: what do you mean with CET? If your input has fixed UTC+1 offset (like Central European Time), then you can use RobG's solution. If you have to consider both CET and CEST, I think that the best soution is to use moment.tz.
Here a live code sample:
const tzGuess = moment.tz.guess()
const toTimeZone = (time) => {
const format = 'DD/MM/YYYY HH:mm'
return moment.tz(time, format, 'Europe/Madrid').tz(tzGuess).format(format)
}
console.log(toTimeZone('17/12/2017 19:34', tzGuess))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.13/moment-timezone-with-data-2012-2022.min.js"></script>
A great resource about timezone is the timezone tag info page.
Without moment.js, parse the string to a Date, treating it as UTC, then adjust for the CET offset (+0100). You can then format it using local time values for the client:
// Parse date in format DD/MM/YYYY HH:mm
// Adjust for CET timezone
function parseCET(s) {
var b = s.split(/\D/);
// Subtract 1 from month and hour
var d = new Date(Date.UTC(b[2], b[1]-1, b[0], b[3]-1, b[4]));
return d;
}
var s = '17/12/2017 19:34';
console.log(parseCET(s).toString());
However, if the time needs to observe daylight saving (CEST) for the source time stamp, you'll need to account for that.
I am using momentjs but having an issue trying to convert a UTC time to a specific timezone (not necessarily local to the current user) that is specified by name 'America/New_York'. This SO question is similar but didn't really help.
My thought process is to create a utc moment obj with the received date from the server and then format that UTC time to the specific timezone for display purposes. A small snippet of how I'm currently approaching this:
var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.tz(cutoffString, 'YYYYMMDD HH:mm:ss', '+00:00');
var displayCutoff =
moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');
console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 04:30:00pm +00:00
My assumption here is that displayCutoff would be the utcCutoff time displayed in 'America/New_York' time. But it currently is displays the same time as the utcCutoff object. I also should mention that using .utc() instead of .tz and trying to manipulate the timezone after applying .local() did not work either.
Any help/guidance would be appreciated.
You can use moment.utc since your input is an UTC string. You can use tz to convert your moment object to a given timezone.
Please note that the tz function converts moment object to a given zone, while you are using moment.tz parsing function that builds a new moment object with the given zone. When you do:
var displayCutoff =
moment.tz(utcCutoff.format('YYYYMMDD HH:mm:ss'), 'YYYYMMDD HH:mm:ss', 'America/New_York');
you are not converting utcCutoff to 'America/New_York' but you are building a new moment object for 20170421 16:30:00 in New York.
Here an updated version of your code:
var cutoffString = '20170421 16:30:00'; // in utc
var utcCutoff = moment.utc(cutoffString, 'YYYYMMDD HH:mm:ss');
var displayCutoff = utcCutoff.clone().tz('America/New_York');
console.log('utcCutoff:', utcCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => utcCutoff: 20170421 04:30:00pm +00:00
console.log('displayCutoff:', displayCutoff.format('YYYYMMDD hh:mm:ssa Z')); // => displayCutoff: 20170421 12:30:00pm -04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.11/moment-timezone-with-data-2010-2020.min.js"></script>
Moment timezone plugin is exactly what you need : http://momentjs.com/timezone/
var dec = moment("2014-12-01T12:00:00Z");
dec.tz('America/New_York').format('ha z'); // 5am PDT
With momentjs-timezone you can convert from any timezone to any other timezone.
You need to specify the start time zone and before formatting the target timezone.
Here is an example which converts a date time from UTC to three other timezones:
const moment = require('moment-timezone')
const start = moment.tz("2021-12-08T10:00:00", "UTC") // original timezone
console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())
This will print out:
2021-12-08T02:00:00-08:00
2021-12-08T15:30:00+05:30
2021-12-08T05:00:00-05:00
Instead of UTC as start timezone you can use any other timezone too, like "Asia/Seoul" and obviously get different results with the same script:
const moment = require('moment-timezone')
const start = moment.tz("2021-12-08T10:00:00", "Asia/Seoul")
console.log(start.tz("America/Los_Angeles").format())
console.log(start.tz("Asia/Calcutta").format())
console.log(start.tz("Canada/Eastern").format())
This prints out:
2021-12-07T17:00:00-08:00
2021-12-08T06:30:00+05:30
2021-12-07T20:00:00-05:00
All momentjs timezones are listed here:
https://gist.github.com/diogocapela/12c6617fc87607d11fd62d2a4f42b02a
There is no need to use MomentJs to convert your timezone to specific timezone. Just follow my given below code, it will work for you :
$(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();//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>
I am new to Javascript and need help on date time api.
I am asking user a date on which some specific task to execute.
I want to convert the given date into UTC format in javascript and pass on to server.
I am converting like below with help of moment js library
var extractTime = new Date(timeof.bgdate);
var d = extractTime.getDate();
var m = extractTime.getMonth();
var y = extractTime.getFullYear();
var h = extractTime.getHours();
var mm = extractTime.getMinutes();
var myDate = moment(new Date(y, m, d, h, mm)).utc().format("YYYY-MM-DD HH:mm");
Created plunk : https://plnkr.co/edit/tjCOoJqXMHGzCD8B5LdL?p=preview
I am in +2 timezone + DST enabled and UTC conversion should give me 16 hour for given date as 18, but it is giving 15 because it is subtracting extra -1 for DST.
My requirement is to ignore daylight savings in UTC conversion.
To create Date object in UTC, we would write
new Date(Date.UTC(2012,02,30));
Without Date.UTC, it takes the locale and creates the Date object. If I have to create a Date object for CET running the program in some part of the world, how would I do it?
You don't create a JavaScript Date object "in" any specific timezone. JavaScript Date objects always work from a milliseconds-since-the-Epoch UTC value. They have methods that apply the local timezone offset and rules (getHours as opposed to getUTCHours), but only the local timezone. You can't set the timezone the Date object uses for its "local" methods.
What you're doing with Date.UTC (correctly, other than the leading 0 on 02) is just initializing the object with the appropriate milliseconds-since-the-Epoch value for that date/time (March 30th at midnight) in UTC, whereas new Date(2012, 2, 30) would have interpreted it as March 30th at midnight local time. There is no difference in the Date object other than the datetime it was initialized with.
If you need a timezone other than local, all you can do is use the UTC version of Date's functions and apply your own offset and rules for the timezone you want to use, which is non-trivial. (The offset is trivial; the rules tend not to be.)
If you go looking, you can find Node modules that handle timezones for you. A quick search for "node timezone" just now gave me timezone as the first hit. It also gave me links to this SO question, this SO question, and this list of timezone modules for Node.
function getCETorCESTDate() {
var localDate = new Date();
var utcOffset = localDate.getTimezoneOffset();
var cetOffset = utcOffset + 60;
var cestOffset = utcOffset + 120;
var cetOffsetInMilliseconds = cetOffset * 60 * 1000;
var cestOffsetInMilliseconds = cestOffset * 60 * 1000;
var cestDateStart = new Date();
var cestDateFinish = new Date();
var localDateTime = localDate.getTime();
var cestDateStartTime;
var cestDateFinishTime;
var result;
cestDateStart.setTime(Date.parse('29 March ' + localDate.getFullYear() + ' 02:00:00 GMT+0100'));
cestDateFinish.setTime(Date.parse('25 October ' + localDate.getFullYear() + ' 03:00:00 GMT+0200'));
cestDateStartTime = cestDateStart.getTime();
cestDateFinishTime = cestDateFinish.getTime();
if(localDateTime >= cestDateStartTime && localDateTime <= cestDateFinishTime) {
result = new Date(localDateTime + cestOffsetInMilliseconds);
} else {
result = new Date(localDateTime + cetOffsetInMilliseconds);
}
return result;
}
How to convert milliseconds in mm/dd/yyyy in different timezones.
I have a datepicker, when I press save, it saves the date in millisecond.
The saved millisecond should display date according to timezone date.
My Code:
var millisecond=1378792800000;
var date=new Date(millisecond);
var date_month = date.getMonth() + 1;
display_date = date_month + "/" + date.getDate() + "/" + date.getFullYear();
The date is differ in different timezones
When my timezone is India GMT then it is 09/10/2013
and when I change my timezone to US Mountain it change to 09/09/2013.
So how can I handle different timezone in javascript.
I would suggest using a third party script such as moment.js to make your life easier
Here is an example: http://jsfiddle.net/cyxgJ/
var ms = 1378792800000;
var date = new moment(ms);
// see <http://momentjs.com/docs/#/manipulating/timezone-offset/>
date = date.zone(120);
document.body.innerHTML = date;