Moment Js UTC to Local Time - javascript

I'm trying to convert UTC time to the local time. I've been following this example from this link: http://jsfiddle.net/FLhpq/4/light/. I can't seem to get the right local output. For example, if its 10: 30 am in here, instead of getting 10:30 ill get 15: 30. Here is my code:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
var localTime = moment.utc(date).toDate();
localTime = moment(localTime).format('YYYY-MM-DD HH:mm:ss');
console.log("moment: " + localTime);
No matter what I do the time always comes out at UTC time. I live in Houston so I know timezone is the issue. I've followed the code in the link but can seem to get the local time. What am I doing wrong?

To convert UTC time to Local you have to use moment.local().
For more info see docs
Example:
var date = moment.utc().format('YYYY-MM-DD HH:mm:ss');
console.log(date); // 2015-09-13 03:39:27
var stillUtc = moment.utc(date).toDate();
var local = moment(stillUtc).local().format('YYYY-MM-DD HH:mm:ss');
console.log(local); // 2015-09-13 09:39:27
Demo:
var date = moment.utc().format();
console.log(date, "- now in UTC");
var local = moment.utc(date).local().format();
console.log(local, "- UTC now to local");
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Try this:
let utcTime = "2017-02-02 08:00:13";
var local_date= moment.utc(utcTime).local().format('YYYY-MM-DD HH:mm:ss');

let utcTime = "2017-02-02 08:00:13.567";
var offset = moment().utcOffset();
var localText = moment.utc(utcTime).utcOffset(offset).format("L LT");
Try this JsFiddle

To convert UTC to local time
let UTC = moment.utc()
let local = moment(UTC).local()
Or you want directly get the local time
let local = moment()
var UTC = moment.utc()
console.log(UTC.format()); // UTC time
var cLocal = UTC.local()
console.log(cLocal.format()); // Convert UTC time
var local = moment();
console.log(local.format()); // Local time
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Note: please update the date format accordingly.
Format Date
__formatDate: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('D-MMM-Y');
}
Format Time
__formatTime: function(myDate){
var ts = moment.utc(myDate);
return ts.local().format('HH:mm');
},

This is old question I see, but I didn't really get what I was looking for. I had a UTC datetime which was formatted without timezone. So I had to do this:
let utcDatetime = '2021-05-31 10:20:00';
let localDatetime = moment(utcDatetime + '+00:00').local().format('YYYY-MM-DD HH:mm:ss');

I've written this Codesandbox for a roundtrip from UTC to local time and from local time to UTC. You can change the timezone and the format. Enjoy!
Full Example on Codesandbox (DEMO):
https://codesandbox.io/s/momentjs-utc-to-local-roundtrip-foj57?file=/src/App.js

This is what worked for me, it required moment-tz as well as moment though.
const guess = moment.utc(date).tz(moment.tz.guess());
const correctTimezone = guess.format()

Here is what I do using Intl api:
let currentTimeZone = new Intl.DateTimeFormat().resolvedOptions().timeZone; // For example: Australia/Sydney
this will return a time zone name. Pass this parameter to the following function to get the time
let dateTime = new Date(date).toLocaleDateString('en-US',{ timeZone: currentTimeZone, hour12: true});
let time = new Date(date).toLocaleTimeString('en-US',{ timeZone: currentTimeZone, hour12: true});
you can also format the time with moment like this:
moment(new Date(`${dateTime} ${time}`)).format('YYYY-MM-DD[T]HH:mm:ss');

I've created one function which converts all the timezones into local time.
Requirements:
1. npm i moment-timezone
function utcToLocal(utcdateTime, tz) {
var zone = moment.tz(tz).format("Z") // Actual zone value e:g +5:30
var zoneValue = zone.replace(/[^0-9: ]/g, "") // Zone value without + - chars
var operator = zone && zone.split("") && zone.split("")[0] === "-" ? "-" : "+" // operator for addition subtraction
var localDateTime
var hours = zoneValue.split(":")[0]
var minutes = zoneValue.split(":")[1]
if (operator === "-") {
localDateTime = moment(utcdateTime).subtract(hours, "hours").subtract(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else if (operator) {
localDateTime = moment(utcdateTime).add(hours, "hours").add(minutes, "minutes").format("YYYY-MM-DD HH:mm:ss")
} else {
localDateTime = "Invalid Timezone Operator"
}
return localDateTime
}
utcToLocal("2019-11-14 07:15:37", "Asia/Kolkata")
//Returns "2019-11-14 12:45:37"

Related

How to convert a date in specific timezone to utc

I am having a date string '2021-09-27 07:43' I also have the info that the date is in (GMT-8:00) Alaska time zone. I am in a different local timezone. When i convert this date to UTC , it is taking my timezone as the reference timezone.
const str = new Date().toLocaleString('en-US', { timeZone: 'Etc/GMT' });
How to do it with respect to a specific time zone as the reference rather than my local time?
You can convert it using moment.js.
see Example:
var input = '2021-09-27 07:43';
var fmt = 'YYYY-MM-DD HH:mm'; // must match the input
var zone = 'Etc/GMT';
var m = moment.tz(input, fmt, zone);
m.utc();
var s = m.format(fmt) // result:
console.log(s);
<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>
Try:
let myDate = "2021-09-27 07:43";
let myDateUTC = new Date(myDate + " UTC-8"); // 2021-09-27T15:43:00.000Z

Changing the time from one format to Local time in JavaScript [duplicate]

Okay, say JSON parse string UTC date as below:
2012-11-29 17:00:34 UTC
Now if I want to convert this UTC date to my local time, how can I do this?
How do I format it to something else like yyyy-MM-dd HH:mm:ss z?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out :/
Try:
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
var offset = new Date().getTimezoneOffset();
offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
Here is another option that outputs mm/dd/yy using toLocaleString():
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
To format your date try the following function:
var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).
Chris
The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
// d = "2021-09-23T15:51:48.31"
console.log(new Date(d + "z").toLocaleDateString()); // gives 9/23/2021
console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}

MomentJS convert from UTC to desired timezone, not just local

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>

Convert date to UTC using moment.js

Probably and easy answer to this but I can't seem to find a way to get moment.js to return a UTC date time in milliseconds. Here is what I am doing:
var date = $("#txt-date").val(),
expires = moment.utc(date);
Any idea what I am doing wrong?
This is found in the documentation. With a library like moment, I urge you to read the entirety of the documentation. It's really important.
Assuming the input text is entered in terms of the users's local time:
var expires = moment(date).valueOf();
If the user is instructed actually enter a UTC date/time, then:
var expires = moment.utc(date).valueOf();
I use this method and it works. ValueOf does not work for me.
moment.utc(yourDate).format()
As of : moment.js version 2.24.0
let's say you have a local date input, this is the proper way to convert your dateTime or Time input to UTC :
var utcStart = new moment("09:00", "HH:mm").utc();
or in case you specify a date
var utcStart = new moment("2019-06-24T09:00", "YYYY-MM-DDTHH:mm").utc();
As you can see the result output will be returned in UTC :
//You can call the format() that will return your UTC date in a string
utcStart.format();
//Result : 2019-06-24T13:00:00
But if you do this as below, it will not convert to UTC :
var myTime = new moment.utc("09:00", "HH:mm");
You're only setting your input to utc time, it's as if your mentioning that myTime is in UTC, ....the output will be 9:00
This will be the answer:
moment.utc(moment(localdate)).format()
localdate = '2020-01-01 12:00:00'
moment(localdate)
//Moment<2020-01-01T12:00:00+08:00>
moment.utc(moment(localdate)).format()
//2020-01-01T04:00:00Z
moment.utc(date).format(...);
is the way to go, since
moment().utc(date).format(...);
does behave weird...
This worked for me. Others might find it useful.
let date = '2020-08-31T00:00:00Z'
moment.utc(moment(date).utc()).format() // returns 2020-08-30T22:00:00Z
If all else fails, just reinitialize with an inverse of your local offset.
var timestamp = new Date();
var inverseOffset = moment(timestamp).utcOffset() * -1;
timestamp = moment().utcOffset( inverseOffset );
timestamp.toISOString(); // This should give you the accurate UTC equivalent.
This moment.utc(stringDate, format).toDate() worked for me.
This moment.utc(date).toDate() not.
here, I'm passing the date object and converting it into UTC time.
$.fn.convertTimeToUTC = function (convertTime) {
if($(this).isObject(convertTime)) {
return moment.tz(convertTime.format("Y-MM-DD HH:mm:ss"), moment.tz.guess()).utc().format("Y-MM-DD HH:mm:ss");
}
};
// Returns if a value is an object
$.fn.isObject = function(value) {
return value && typeof value === 'object';
};
//you can call it as below
$(this).convertTimeToUTC(date);
Read this documentation of moment.js here.
See below example and output where I convert GMT time to local time (my zone is IST) and then I convert local time to GMT.
// convert GMT to local time
console.log('Server time:' + data[i].locationServerTime)
let serv_utc = moment.utc(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment(serv_utc,"YYYY-MM-DD HH:mm:ss").tz(self.zone_name).format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to local time:' + data[i].locationServerTime)
// convert local time to GMT
console.log('local time:' + data[i].locationServerTime)
let serv_utc = moment(data[i].locationServerTime, "YYYY-MM-DD HH:mm:ss").toDate();
console.log('serv_utc:' + serv_utc)
data[i].locationServerTime = moment.utc(serv_utc,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
console.log('Converted to server time:' + data[i].locationServerTime)
Output is
Server time:2019-12-19 09:28:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to local time:2019-12-19 14:58:13
local time:2019-12-19 14:58:13
serv_utc:Thu Dec 19 2019 14:58:13 GMT+0530 (India Standard Time)
Converted to server time:2019-12-19 09:28:13
This worked for me:
const localtime = 1622516400000
moment(localtime).utc(true).format()
We can get 2 UTC date formats.
const date = '2021-07-20T18:30:00Z';
moment.utc(moment(date).utc()).format(); // 2021-07-19T18:30:00Z
moment.utc(moment(date).utc()).toISOString(); // 2021-07-20T18:30:00.000Z (Complete ISO-8601)
This works in my case.
Library: "moment": "^2.29.1",
moment().utc().format()
Don't you need something to compare and then retrieve the milliseconds?
For instance:
let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC
With that you have the expiring date in UTC.
Now you can get the "right-now" date in UTC and compare:
var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();

Javascript to convert UTC to local time

Okay, say JSON parse string UTC date as below:
2012-11-29 17:00:34 UTC
Now if I want to convert this UTC date to my local time, how can I do this?
How do I format it to something else like yyyy-MM-dd HH:mm:ss z?
This date.toString('yyyy-MM-dd HH:mm:ss z'); never work out :/
Try:
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString();
var offset = new Date().getTimezoneOffset();
offset will be the interval in minutes from Local time to UTC. To get Local time from a UTC date, you would then subtract the minutes from your date.
utc_date.setMinutes(utc_date.getMinutes() - offset);
Here is another option that outputs mm/dd/yy using toLocaleString():
const date = new Date('2012-11-29 17:00:34 UTC');
date.toLocaleString();
//output 11/29/2012
To format your date try the following function:
var d = new Date();
var fromatted = d.toLocaleFormat("%d.%m.%Y %H:%M (%a)");
But the downside of this is, that it's a non-standard function, which is not working in Chrome, but working in FF (afaik).
Chris
The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format
You could take a look at date-and-time api for easily date manipulation.
let now = date.format(new Date(), 'YYYY-MM-DD HH:mm:ss', true);
console.log(now);
<script src="https://cdn.jsdelivr.net/npm/date-and-time/date-and-time.min.js"></script>
This should work
var date = new Date('2012-11-29 17:00:34 UTC');
date.toString()
This works for both Chrome and Firefox.
Not tested on other browsers.
const convertToLocalTime = (dateTime, notStanderdFormat = true) => {
if (dateTime !== null && dateTime !== undefined) {
if (notStanderdFormat) {
// works for 2021-02-21 04:01:19
// convert to 2021-02-21T04:01:19.000000Z format before convert to local time
const splited = dateTime.split(" ");
let convertedDateTime = `${splited[0]}T${splited[1]}.000000Z`;
const date = new Date(convertedDateTime);
return date.toString();
} else {
// works for 2021-02-20T17:52:45.000000Z or 1613639329186
const date = new Date(dateTime);
return date.toString();
}
} else {
return "Unknown";
}
};
// TEST
console.log(convertToLocalTime('2012-11-29 17:00:34 UTC'));
// d = "2021-09-23T15:51:48.31"
console.log(new Date(d + "z").toLocaleDateString()); // gives 9/23/2021
console.log(new Date(d + "z").toLocaleString()); // gives 9/23/2021, 10:51:48 AM
console.log(new Date(d + "z").toLocaleTimeString()); // gives 10:51:48 AM
/*
* convert server time to local time
* simbu
*/
function convertTime(serverdate) {
var date = new Date(serverdate);
// convert to utc time
var toutc = date.toUTCString();
//convert to local time
var locdat = new Date(toutc + " UTC");
return locdat;
}

Categories