How to convert utc time to local time on frontend [duplicate] - javascript

From the server I get a datetime variable in this format: 6/29/2011 4:52:48 PM and it is in UTC time. I want to convert it to the current user’s browser time zone using JavaScript.
How this can be done using JavaScript or jQuery?

Append 'UTC' to the string before converting it to a date in javascript:
var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

In my point of view servers should always in the general case return a datetime in the standardized ISO 8601-format.
More info here:
http://www.w3.org/TR/NOTE-datetime
https://en.wikipedia.org/wiki/ISO_8601
IN this case the server would return '2011-06-29T16:52:48.000Z' which would feed directly into the JS Date object.
var utcDate = '2011-06-29T16:52:48.000Z'; // ISO-8601 formatted date returned from server
var localDate = new Date(utcDate);
The localDate will be in the right local time which in my case would be two hours later (DK time).
You really don't have to do all this parsing which just complicates stuff, as long as you are consistent with what format to expect from the server.

This is an universal solution:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime()+date.getTimezoneOffset()*60*1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));
Display the date based on the client local setting:
date.toLocaleString();

For me above solutions didn't work.
With IE the UTC date-time conversion to local is little tricky.
For me, the date-time from web API is '2018-02-15T05:37:26.007' and I wanted to convert as per local timezone so I used below code in JavaScript.
var createdDateTime = new Date('2018-02-15T05:37:26.007' + 'Z');

You should get the (UTC) offset (in minutes) of the client:
var offset = new Date().getTimezoneOffset();
And then do the correspondent adding or substraction to the time you get from the server.
Hope this helps.

This works for me:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() - date.getTimezoneOffset()*60*1000);
return newDate;
}

Put this function in your head:
<script type="text/javascript">
function localize(t)
{
var d=new Date(t+" UTC");
document.write(d.toString());
}
</script>
Then generate the following for each date in the body of your page:
<script type="text/javascript">localize("6/29/2011 4:52:48 PM");</script>
To remove the GMT and time zone, change the following line:
document.write(d.toString().replace(/GMT.*/g,""));

This is a simplified solution based on Adorjan Princ´s answer:
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date);
newDate.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return newDate;
}
or simpler (though it mutates the original date):
function convertUTCDateToLocalDate(date) {
date.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return date;
}
Usage:
var date = convertUTCDateToLocalDate(new Date(date_string_you_received));

After trying a few others posted here without good results, this seemed to work for me:
convertUTCDateToLocalDate: function (date) {
return new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));
}
And this works to go the opposite way, from Local Date to UTC:
convertLocalDatetoUTCDate: function(date){
return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}

Add the time zone at the end, in this case 'UTC':
theDate = new Date( Date.parse('6/29/2011 4:52:48 PM UTC'));
after that, use toLocale()* function families to display the date in the correct locale
theDate.toLocaleString(); // "6/29/2011, 9:52:48 AM"
theDate.toLocaleTimeString(); // "9:52:48 AM"
theDate.toLocaleDateString(); // "6/29/2011"

if you have
"2021-12-28T18:00:45.959Z" format
you can use this in js :
// myDateTime is 2021-12-28T18:00:45.959Z
myDate = new Date(myDateTime).toLocaleDateString('en-US');
// myDate is 12/28/2021
myTime = new Date(myDateTime).toLocaleTimeString('en-US');
// myTime is 9:30:45 PM
you just have to put your area string instead of "en-US" (e.g. "fa-IR").
also you can use options for toLocaleTimeString like { hour: '2-digit', minute: '2-digit' }
myTime = new Date(myDateTime).toLocaleTimeString('en-US',{ hour: '2-digit', minute: '2-digit' });
// myTime is 09:30 PM
more information for toLocaleTimeString and toLocaleDateString

Use this for UTC and Local time convert and vice versa.
//Covert datetime by GMT offset
//If toUTC is true then return UTC time other wise return local time
function convertLocalDateToUTCDate(date, toUTC) {
date = new Date(date);
//Local time converted to UTC
console.log("Time: " + date);
var localOffset = date.getTimezoneOffset() * 60000;
var localTime = date.getTime();
if (toUTC) {
date = localTime + localOffset;
} else {
date = localTime - localOffset;
}
date = new Date(date);
console.log("Converted time: " + date);
return date;
}

Matt's answer is missing the fact that the daylight savings time could be different between Date() and the date time it needs to convert - here is my solution:
function ConvertUTCTimeToLocalTime(UTCDateString)
{
var convertdLocalTime = new Date(UTCDateString);
var hourOffset = convertdLocalTime.getTimezoneOffset() / 60;
convertdLocalTime.setHours( convertdLocalTime.getHours() + hourOffset );
return convertdLocalTime;
}
And the results in the debugger:
UTCDateString: "2014-02-26T00:00:00"
convertdLocalTime: Wed Feb 26 2014 00:00:00 GMT-0800 (Pacific Standard Time)

In case you don't mind usingmoment.js and your time is in UTC just use the following:
moment.utc('6/29/2011 4:52:48 PM').toDate();
if your time is not in utc but any other locale known to you, then use following:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY', 'fr').toDate();
if your time is already in local, then use following:
moment('6/29/2011 4:52:48 PM', 'MM-DD-YYYY');

To me the simplest seemed using
datetime.setUTCHours(datetime.getHours());
datetime.setUTCMinutes(datetime.getMinutes());
(i thought the first line could be enough but there are timezones which are off in fractions of hours)

This is what I'm doing to convert UTC to my Local Time:
const dataDate = '2020-09-15 07:08:08'
const utcDate = new Date(dataDate);
const myLocalDate = new Date(Date.UTC(
utcDate.getFullYear(),
utcDate.getMonth(),
utcDate.getDate(),
utcDate.getHours(),
utcDate.getMinutes()
));
document.getElementById("dataDate").innerHTML = dataDate;
document.getElementById("myLocalDate").innerHTML = myLocalDate;
<p>UTC<p>
<p id="dataDate"></p>
<p>Local(GMT +7)<p>
<p id="myLocalDate"></p>
Result: Tue Sep 15 2020 14:08:00 GMT+0700 (Indochina Time).

Using YYYY-MM-DD hh:mm:ss format :
var date = new Date('2011-06-29T16:52:48+00:00');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"
For converting from the YYYY-MM-DD hh:mm:ss format, make sure your date follow the ISO 8601 format.
Year:
YYYY (eg 1997)
Year and month:
YYYY-MM (eg 1997-07)
Complete date:
YYYY-MM-DD (eg 1997-07-16)
Complete date plus hours and minutes:
YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00)
Complete date plus hours, minutes and seconds:
YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00)
Complete date plus hours, minutes, seconds and a decimal fraction of a second
YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where:
YYYY = four-digit year
MM = two-digit month (01=January, etc.)
DD = two-digit day of month (01 through 31)
hh = two digits of hour (00 through 23) (am/pm NOT allowed)
mm = two digits of minute (00 through 59)
ss = two digits of second (00 through 59)
s = one or more digits representing a decimal fraction of a second
TZD = time zone designator (Z or +hh:mm or -hh:mm)
Important things to note
You must separate the date and the time by a T, a space will not work in some browsers
You must set the timezone using this format +hh:mm, using a string for a timezone (ex. : 'UTC') will not work in many browsers. +hh:mm represent the offset from the UTC timezone.

A JSON date string (serialized in C#) looks like "2015-10-13T18:58:17".
In angular, (following Hulvej) make a localdate filter:
myFilters.filter('localdate', function () {
return function(input) {
var date = new Date(input + '.000Z');
return date;
};
})
Then, display local time like:
{{order.createDate | localdate | date : 'MMM d, y h:mm a' }}

For me, this works well
if (typeof date === "number") {
time = new Date(date).toLocaleString();
} else if (typeof date === "string"){
time = new Date(`${date} UTC`).toLocaleString();
}

I Answering This If Any one want function that display converted time to specific id element and apply date format string yyyy-mm-dd
here date1 is string and ids is id of element that time going to display.
function convertUTCDateToLocalDate(date1, ids)
{
var newDate = new Date();
var ary = date1.split(" ");
var ary2 = ary[0].split("-");
var ary1 = ary[1].split(":");
var month_short = Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
newDate.setUTCHours(parseInt(ary1[0]));
newDate.setUTCMinutes(ary1[1]);
newDate.setUTCSeconds(ary1[2]);
newDate.setUTCFullYear(ary2[0]);
newDate.setUTCMonth(ary2[1]);
newDate.setUTCDate(ary2[2]);
ids = document.getElementById(ids);
ids.innerHTML = " " + newDate.getDate() + "-" + month_short[newDate.getMonth() - 1] + "-" + newDate.getFullYear() + " " + newDate.getHours() + ":" + newDate.getMinutes() + ":" + newDate.getSeconds();
}
i know that answer has been already accepted but i get here cause of google and i did solve with getting inspiration from accepted answer so i did want to just share it if someone need.

#Adorojan's answer is almost correct. But addition of offset is not correct since offset value will be negative if browser date is ahead of GMT and vice versa.
Below is the solution which I came with and is working perfectly fine for me:
// Input time in UTC
var inputInUtc = "6/29/2011 4:52:48";
var dateInUtc = new Date(Date.parse(inputInUtc+" UTC"));
//Print date in UTC time
document.write("Date in UTC : " + dateInUtc.toISOString()+"<br>");
var dateInLocalTz = convertUtcToLocalTz(dateInUtc);
//Print date in local time
document.write("Date in Local : " + dateInLocalTz.toISOString());
function convertUtcToLocalTz(dateInUtc) {
//Convert to local timezone
return new Date(dateInUtc.getTime() - dateInUtc.getTimezoneOffset()*60*1000);
}

Based on #digitalbath answer, here is a small function to grab the UTC timestamp and display the local time in a given DOM element (using jQuery for this last part):
https://jsfiddle.net/moriz/6ktb4sv8/1/
<div id="eventTimestamp" class="timeStamp">
</div>
<script type="text/javascript">
// Convert UTC timestamp to local time and display in specified DOM element
function convertAndDisplayUTCtime(date,hour,minutes,elementID) {
var eventDate = new Date(''+date+' '+hour+':'+minutes+':00 UTC');
eventDate.toString();
$('#'+elementID).html(eventDate);
}
convertAndDisplayUTCtime('06/03/2015',16,32,'eventTimestamp');
</script>

You can use momentjs ,moment(date).format() will always give result in local date.
Bonus , you can format in any way you want. For eg.
moment().format('MMMM Do YYYY, h:mm:ss a'); // September 14th 2018, 12:51:03 pm
moment().format('dddd'); // Friday
moment().format("MMM Do YY");
For more details you can refer Moment js website

this worked well for me with safari/chrome/firefox :
const localDate = new Date(`${utcDate.replace(/-/g, '/')} UTC`);

I believe this is the best solution:
let date = new Date(objDate);
date.setMinutes(date.getTimezoneOffset());
This will update your date by the offset appropriately since it is presented in minutes.

tl;dr (new Date('6/29/2011 4:52:48 PM UTC')).toString()
The source string must specify a time zone or UTC.
One-liner:
(new Date('6/29/2011 4:52:48 PM UTC')).toString()
Result in one of my web browsers:
"Wed Jun 29 2011 09:52:48 GMT-0700 (Pacific Daylight Time)"
This approach even selects standard/daylight time appropriately.
(new Date('1/29/2011 4:52:48 PM UTC')).toString()
Result in my browser:
"Sat Jan 29 2011 08:52:48 GMT-0800 (Pacific Standard Time)"

using dayjs library:
(new Date()).toISOString(); // returns 2021-03-26T09:58:57.156Z (GMT time)
dayjs().format('YYYY-MM-DD HH:mm:ss,SSS'); // returns 2021-03-26 10:58:57,156 (local time)
(in nodejs, you must do before using it: const dayjs = require('dayjs');
in other environtments, read dayjs documentation.)

This works on my side
Option 1: If date format is something like "yyyy-mm-dd" or "yyyy-mm-dd H:n:s", ex: "2021-12-16 06:07:40"
With this format It doesnt really know if its a local format or a UTC time. So since we know that the date is a UTC we have to make sure that JS will know that its a UTC. So we have to set the date as UTC.
function setDateAsUTC(d) {
let date = new Date(d);
return new Date(
Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds()
)
);
}
and then use it
let d = "2021-12-16 06:07:40";
setDateAsUTC(d).toLocaleString();
// output: 12/16/2021, 6:07:40 AM
Options 2: If UTC date format is ISO-8601. Mostly servers timestampz format are in ISO-8601 ex: '2011-06-29T16:52:48.000Z'. With this we can just pass it to the date function and toLocaleString() function.
let newDate = "2011-06-29T16:52:48.000Z"
new Date(newDate).toLocaleString();
//output: 6/29/2011, 4:52:48 PM

In JavaScript I used:
var updaated_time= "2022-10-25T06:47:42.000Z"
{{updaated_time | date: 'dd-MM-yyyy HH:mm'}} //output: 26-10-2022 12:00

I wrote a nice little script that takes a UTC epoch and converts it the client system timezone and returns it in d/m/Y H:i:s (like the PHP date function) format:
getTimezoneDate = function ( e ) {
function p(s) { return (s < 10) ? '0' + s : s; }
var t = new Date(0);
t.setUTCSeconds(e);
var d = p(t.getDate()),
m = p(t.getMonth()+1),
Y = p(t.getFullYear()),
H = p(t.getHours()),
i = p(t.getMinutes()),
s = p(t.getSeconds());
d = [d, m, Y].join('/') + ' ' + [H, i, s].join(':');
return d;
};

Related

Convert HH:mm to UTC date time in JavaScript using date-fns

I'm working on an appointment booking React app where a teacher can set their virtual office hours in the form of a time slot.
let availability = ["09:00", "17:00"]; // from 9 AM to 5 PM local time
Since this time is local to the teacher, I'd like to store it as UTC time in the ISO 8601 format so that if a student is in a different region, I can parse it on the client and show this time in their appropriate timezone.
I tried using the parse function from date-fns#2.22.1 like this
parse('09:00', 'HH:mm', new Date()); // => Wed Jan 01 0020 00:00:00 GMT-0456 (Eastern Daylight Time)
But, this didn't return the time in my timezone (Central Standard Time).
Is there a way to represent this local time slot in UTC?
Not sure if this is your desired output
const inputTime = "09:00";
const outputDate = new Date(new Date().toJSON().slice(0, 10) + " " + inputTime).toUTCString();
console.log(outputDate);
I came to a solution which was inspired by #Anas Abdullah Al. Here are two simple functions which will convert from both UTC and a user's local time.
const format = window.dateFns.format;
const convertLocalToUTC = (localTime) => {
if (!localTime) {
throw new Error("Time can't be empty");
}
return new Date(`${new Date().toJSON().slice(0, 10)} ${localTime}`)
.toISOString()
.slice(11, 16);
};
const convertUTCToLocal = (UTCTime) => {
if (!UTCTime) {
throw new Error("Time can't be empty");
}
const currentUTCDate = new Date().toISOString().substring(0, 10);
const inputUTCDateTime = `${currentUTCDate}T${UTCTime}:00.000Z`;
return format(new Date(inputUTCDateTime), "HH:mm");
};
const UTCTime = "14:00";
const localTime = "09:00";
console.log(convertLocalToUTC(localTime)); // 14:00 UTC
console.log(convertUTCToLocal(UTCTime)); // 09:00 CST
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js"></script>
Hope this helps someone else.

Json date format conversion subtracting 1 day

The date format i receive from JSON is like this :-
/Date(1412101800000)/
When i convert this into dateformat, i get 1 day minus.
I am using following code :-
var dateFormat = new Date(parseInt(obj['DATEOFJOINING'].substr(6))).toISOString().substr(0, 10);
dateFormat results in 2014-09-30
The Original Date which comes from Db is 2014-10-01
Why is this happening? How to get perfect date?
It's a timestamp.
new Date(parseInt('/Date(1412101800000)/'.substr(6)));
Just set a right timezone.
var dateFormat = new Date(parseInt('/Date(1412101800000)/'.substr(6)));
dateFormat.setTime( dateFormat.getTime() + dateFormat.getTimezoneOffset()*60*1000 );
Date in your timezone*: 30/09/2014 19:30:00
Date in Los Angeles*: 30/09/2014 11:30:00
Date in Berlin* :30/09/2014 19:30:00
Date in Beijing*: 01/10/2014 01:30:00
Date in New York* :30/09/2014 13:30:00
For example
var dateFormat = new Date(parseInt('/Date(1412101800000)/'.substr(6)));
dateFormat.setTime( dateFormat.getTime() + dateFormat.getTimezoneOffset()*(-10*100000));
Date {Wed Oct 01 2014 12:10:00 GMT+0100 (BST)}
As #madforstrength commented, it uses the offset from GMT.
To get the offset in minutes you can try:
var d = new Date()
var n = d.getTimezoneOffset();
and adjust for your local time.
You can see a reference here.
This is due to the clients timezone. Use Date.prototype.getTimezoneOffset to get the offset:
var date = new Date(1412101800000);
var gmtDate = new Date(date.valueOf() + date.getTimezoneOffset() * 60 * 1000);

convert custom date string to date object

How can I convert a string representation of a date to a real javascript date object?
the date has the following format
E MMM dd HH:mm:ss Z yyyy
e.g.
Sat Jun 30 00:00:00 CEST 2012
Thanks in advance
EDIT:
My working solution is based on the accepted answer. To get it work in IE8, you have to replace the month part (e.g. Jun) with the months number (e.g. 5 for June, because January is 0)
Your date string can mostly be parsed as is but CEST isn't a valid time zone in ISO 8601, so you'll have to manually replace it with +0200.
A simple solution thus might be :
var str = "Sat Jun 30 00:00:00 CEST 2012";
str = str.replace(/CEST/, '+0200');
var date = new Date(str);
If you want to support other time zones defined by their names, you'll have to find their possible values and the relevant offset. You can register them in a map :
var replacements = {
"ACDT": "+1030",
"CEST": "+0200",
...
};
for (var key in replacements) str = str.replace(key, replacements[key]);
var date = new Date(str);
This might be a good list of time zone abbreviation.
You can use following code to convert string into datetime:
var sDate = "01/09/2013 01:10:59";
var dateArray = sDate.split('/');
var day = dateArray[1];
// Attention! JavaScript consider months in the range 0 - 11
var month = dateArray[0] - 1;
var year = dateArray[2].split(' ')[0];
var hour = (dateArray[2].split(' ')[1]).split(':')[0];
var minute = (dateArray[2].split(' ')[1]).split(':')[1];
var objDt = new Date(year, month, day, hour, minute);
alert(objDt);

How to the get the beginning of day of a date in javascript -- factoring in timezone

I am struggling to find out the beginning of day factoring in timezones in javascript. Consider the following:
var raw_time = new Date(this.created_at);
var offset_time = new Date(raw_hour.getTime() + time_zone_offset_in_ms);
// This resets timezone to server timezone
var offset_day = new Date(offset_time.setHours(0,0,0,0))
// always returns 2011-12-08 05:00:00 UTC, no matter what the offset was!
// This has the same issue:
var another_approach_offset_day = new Date(offset_time.getFullYear(),offset_time.getMonth(),offset_time.getHours())
I expect when i pass a Pacific Timezone offset, to get: 2011-12-08 08:00:00 UTC and so on.
What is the correct way to achieve this?
I think that part of the issue is that setHours method sets the hour (from 0 to 23), according to local time.
Also note that I am using javascript embedded in mongo, so I am unable to use any additional libraries.
Thanks!
Jeez, so this was really hard for me, but here is the final solution that I came up with the following solution. The trick was I need to use setHours or SetUTCHours to get the beginning of a day -- the only choices I have are system time and UTC. So I get the beginning of a UTC day, then add back the offset!
// Goal is given a time and a timezone, find the beginning of day
function(timestamp,selected_timezone_offset) {
var raw_time = new Date(timestamp)
var offset_time = new Date(raw_time.getTime() + selected_timezone_offset);
offset_time.setUTCHours(0,0,0,0);
var beginning_of_day = new Date(offset_time.getTime() - selected_timezone_offset);
return beginning_of_day;
}
In JavaScript all dates are stored as UTC. That is, the serial number returned by date.valueOf() is the number of milliseconds since 1970-01-01 00:00:00 UTC. But, when you examine a date via .toString() or .getHours(), etc., you get the value in local time. That is, the local time of the system running the script. You can get the value in UTC with methods like .toUTCString() or .getUTCHours(), etc.
So, you can't get a date in an arbitrary timezone, it's all UTC (or local). But, of course, you can get a string representation of a date in whatever timezone you like if you know the UTC offset. The easiest way would be to subtract the UTC offset from the date and call .getUTCHours() or .toUTCString() or whatever you need:
var d = new Date();
d.setMinutes(d.getMinutes() - 480); // get pacific standard time
d.toUTCString(); // returns "Fri, 9 Dec 2011 12:56:53 UTC"
Of course, you'll need to ignore that "UTC" at the end if you use .toUTCString(). You could just go:
d.toUTCString().replace(/UTC$/, "PST");
Edit: Don't worry about when timezones overlap date boundaries. If you pass setHours() a negative number, it will subtract those hours from midnight yesterday. Eg:
var d = new Date(2011, 11, 10, 15); // d represents Dec 10, 2011 at 3pm local time
d.setHours(-1); // d represents Dec 9, 2011 at 11pm local time
d.setHours(-24); // d represents Dec 8, 2011 at 12am local time
d.setHours(52); // d represents Dec 10, 2011 at 4am local time
Where does the time_zone_offset_in_ms variable you use come from? Perhaps it is unreliable, and you should be using Date's getTimezoneOffset() method. There is an example at the following URL:
http://www.w3schools.com/jsref/jsref_getTimezoneOffset.asp
If you know the date from a different date string you can do the following:
var currentDate = new Date(this.$picker.data('date'));
var today = new Date();
today.setHours(0, -currentDate.getTimezoneOffset(), 0, 0);
(based on the codebase for a project I did)
var aDate = new Date();
var startOfTheDay = new Date(aDate.getTime() - aDate.getTime() % 86400000)
Will create the beginning of the day, of the day in question
You can make use of Intl.DateTimeFormat. This is also how luxon handles timezones.
The code below can convert any date with any timezone to its beginging/end of the time.
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));

Convert UTC Epoch to local date

I have been fighting with this for a bit now. I’m trying to convert epoch to a date object. The epoch is sent to me in UTC. Whenever you pass new Date() an epoch, it assumes it’s local epoch. I tried creating a UTC object, then using setTime() to adjust it to the proper epoch, but the only method that seems useful is toUTCString() and strings don’t help me. If I pass that string into a new date, it should notice that it’s UTC, but it doesn’t.
new Date( new Date().toUTCString() ).toLocaleString()
My next attempt was to try to get the difference between local current epoch and UTC current epoch, but I wasn’t able to get that either.
new Date( new Date().toUTCString() ).getTime() - new Date().getTime()
It’s only giving me very small differences, under 1000, which is in milliseconds.
Any suggestions?
I think I have a simpler solution -- set the initial date to the epoch and add UTC units. Say you have a UTC epoch var stored in seconds. How about 1234567890. To convert that to a proper date in the local time zone:
var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);
d is now a date (in my time zone) set to Fri Feb 13 2009 18:31:30 GMT-0500 (EST)
It's easy, new Date() just takes milliseconds, e.g.
new Date(1394104654000)
> Thu Mar 06 2014 06:17:34 GMT-0500 (EST)
And just for the logs, I did this using Moment.js library, which I was using for formatting anyway.
moment.utc(1234567890000).local()
>Fri Feb 13 2009 19:01:30 GMT-0430 (VET)
Epoch time is in seconds from Jan. 1, 1970. date.getTime() returns milliseconds from Jan. 1, 1970, so.. if you have an epoch timestamp, convert it to a javascript timestamp by multiplying by 1000.
function epochToJsDate(ts){
// ts = epoch timestamp
// returns date obj
return new Date(ts*1000);
}
function jsDateToEpoch(d){
// d = javascript date obj
// returns epoch timestamp
return (d.getTime()-d.getMilliseconds())/1000;
}
function ToLocalDate (inDate) {
var date = new Date();
date.setTime(inDate.valueOf() - 60000 * inDate.getTimezoneOffset());
return date;
}
Epoch time (i.e. Unix Epoch time) is nearly always the number of seconds that have expired since 1st Jan 1970 00:00:00 (UTC time), not the number of milliseconds which some of the answers here have implied.
https://en.wikipedia.org/wiki/Unix_time
Therefore, if you have been given a Unix Epoch time value it will probably be in seconds, and will look something like 1547035195. If you want to make this human readable in JavaScript, you need to convert the value to milliseconds, and pass that value into the Date(value) constructor, e.g.:
const unixEpochTimeMS = 1547035195 * 1000;
const d = new Date(unixEpochTimeMS);
// Careful, the string output here can vary by implementation...
const strDate = d.toLocaleString();
You don't need to do the d.setUTCMilliseconds(0) step in the accepted answer because the JavaScript Date(value) constructor takes a UTC value in milliseconds (not a local time).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#Syntax
Also note that you should avoid using the Date(...) constructor that takes a string datetime representation, this is not recommended (see the link above).
var myDate = new Date( your epoch date *1000);
source - https://www.epochconverter.com/programming/#javascript
To convert the current epoch time in [ms] to a 24-hour time. You might need to specify the option to disable 12-hour format.
$ node.exe -e "var date = new Date(Date.now()); console.log(date.toLocaleString('en-GB', { hour12:false } ));"
2/7/2018, 19:35:24
or as JS:
var date = new Date(Date.now());
console.log(date.toLocaleString('en-GB', { hour12:false } ));
// 2/7/2018, 19:35:24
console.log(date.toLocaleString('en-GB', { hour:'numeric', minute:'numeric', second:'numeric', hour12:false } ));
// 19:35:24
Note: The use of en-GB here, is just a (random) choice of a place using the 24 hour format, it is not your timezone!
Addition to the above answer by #djechlin
d = '1394104654000';
new Date(parseInt(d));
converts EPOCH time to human readable date. Just don't forget that type of EPOCH time must be an Integer.
The Easiest Way
If you have the unix epoch in milliseconds, in my case - 1601209912824
convert it into a Date Object as so
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toString()
output -
Sun Sep 27 2020 18:01:52 GMT+0530 (India Standard Time)
if you want the date in UTC -
const dateObject = new Date(milliseconds)
const humanDateFormat = dateObject.toUTCString()
Now you can format it as you please.
Considering, you have epoch_time available,
// for eg. epoch_time = 1487086694.213
var date = new Date(epoch_time * 1000); // multiply by 1000 for milliseconds
var date_string = date.toLocaleString('en-GB'); // 24 hour format
The simplest solution I've found to this, is:
var timestamp = Date.now(), // returns milliseconds since epoch time
normalisedTime = new Date(timestamp);
Notice this doesn't have the * 1000 at the end of new Date(timestamp) statement as this (for me anyway!) always seems to give out the wrong date, ie instead of giving the year 2019 it gives the year as 51015, so just bear that in mind.
EDIT
var utcDate = new Date(incomingUTCepoch);
var date = new Date();
date.setUTCDate(utcDate.getDate());
date.setUTCHours(utcDate.getHours());
date.setUTCMonth(utcDate.getMonth());
date.setUTCMinutes(utcDate.getMinutes());
date.setUTCSeconds(utcDate.getSeconds());
date.setUTCMilliseconds(utcDate.getMilliseconds());
EDIT fixed
Are you just asking to convert a UTC string to a "local" string? You could do:
var utc_string = '2011-09-05 20:05:15';
var local_string = (function(dtstr) {
var t0 = new Date(dtstr);
var t1 = Date.parse(t0.toUTCString().replace('GMT', ''));
var t2 = (2 * t0) - t1;
return new Date(t2).toString();
})(utc_string);
If you prefer to resolve timestamps and dates conversions from and to UTC and local time without libraries like moment.js, take a look at the option below.
For applications that use UTC timestamps, you may need to show the date in the browser considering the local timezone and daylight savings when applicable. Editing a date that is in a different daylight savings time even though in the same timezone can be tricky.
The Number and Date extensions below allow you to show and get dates in the timezone of the timestamps. For example, lets say you are in Vancouver, if you are editing a date in July or in December, it can mean you are editing a date in PST or PDT.
I recommend you to check the Code Snippet down below to test this solution.
Conversions from milliseconds
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
Conversions from dates
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
Usage
// Adds the timezone and daylight savings if applicable
(1499670000000).toLocalDate();
// Eliminates the timezone and daylight savings if applicable
new Date(2017, 6, 10).getUTCTime();
See it for yourself
// Extending Number
Number.prototype.toLocalDate = function () {
var value = new Date(this);
value.setHours(value.getHours() + (value.getTimezoneOffset() / 60));
return value;
};
Number.prototype.toUTCDate = function () {
var value = new Date(this);
value.setHours(value.getHours() - (value.getTimezoneOffset() / 60));
return value;
};
// Extending Date
Date.prototype.getUTCTime = function () {
return this.getTime() - (this.getTimezoneOffset() * 60000);
};
// Getting the demo to work
document.getElementById('m-to-local-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-local-display'),
value = document.getElementById('m-to-local').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toLocalDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('m-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('m-to-utc-display'),
value = document.getElementById('m-to-utc').value,
milliseconds = parseInt(value);
if (typeof milliseconds === 'number')
displayElement.innerText = (milliseconds).toUTCDate().toISOString();
else
displayElement.innerText = 'Set a value';
}, false);
document.getElementById('date-to-utc-button').addEventListener('click', function () {
var displayElement = document.getElementById('date-to-utc-display'),
yearValue = document.getElementById('date-to-utc-year').value || '1970',
monthValue = document.getElementById('date-to-utc-month').value || '0',
dayValue = document.getElementById('date-to-utc-day').value || '1',
hourValue = document.getElementById('date-to-utc-hour').value || '0',
minuteValue = document.getElementById('date-to-utc-minute').value || '0',
secondValue = document.getElementById('date-to-utc-second').value || '0',
year = parseInt(yearValue),
month = parseInt(monthValue),
day = parseInt(dayValue),
hour = parseInt(hourValue),
minute = parseInt(minuteValue),
second = parseInt(secondValue);
displayElement.innerText = new Date(year, month, day, hour, minute, second).getUTCTime();
}, false);
<link href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.11/semantic.css" rel="stylesheet"/>
<div class="ui container">
<p></p>
<h3>Milliseconds to local date</h3>
<input id="m-to-local" placeholder="Timestamp" value="0" /> <button id="m-to-local-button">Convert</button>
<em id="m-to-local-display">Set a value</em>
<h3>Milliseconds to UTC date</h3>
<input id="m-to-utc" placeholder="Timestamp" value="0" /> <button id="m-to-utc-button">Convert</button>
<em id="m-to-utc-display">Set a value</em>
<h3>Date to milliseconds in UTC</h3>
<input id="date-to-utc-year" placeholder="Year" style="width: 4em;" />
<input id="date-to-utc-month" placeholder="Month" style="width: 4em;" />
<input id="date-to-utc-day" placeholder="Day" style="width: 4em;" />
<input id="date-to-utc-hour" placeholder="Hour" style="width: 4em;" />
<input id="date-to-utc-minute" placeholder="Minute" style="width: 4em;" />
<input id="date-to-utc-second" placeholder="Second" style="width: 4em;" />
<button id="date-to-utc-button">Convert</button>
<em id="date-to-utc-display">Set the values</em>
</div>
#Amjad, good idea, but a better implementation would be:
Date.prototype.setUTCTime = function(UTCTimestamp) {
var UTCDate = new Date(UTCTimestamp);
this.setUTCFullYear(UTCDate.getFullYear(), UTCDate.getMonth(), UTCDate.getDate());
this.setUTCHours(UTCDate.getHours(), UTCDate.getMinutes(), UTCDate.getSeconds(), UTCDate.getMilliseconds());
return this.getTime();
}

Categories