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;
};
I know there are tons of questions about date formatting, but I'm stuck with a conversion.
I have a string so formatted: mag 11, 2021 2:31:00 pm ("mag" is the abbreviation of May in italian).
I want to convert it in date so I can change it to the format DD/MM/YYYY HH:MM:ss (in this case "11/05/2021 14:31").
I tried to use the new Date or Date.parse functions, but in console it returns me the error 'Invalid date'.
Here's what I tried:
let a = "mag 11, 2021 2:31:00 pm";
let b = new Date(a);
console.log(b);
console output -----> Invalid Date
let a = "mag 11, 2021 2:31:00 pm";
let b = Date.parse(a);
console.log(b);
console output -----> NaN
Any idea? Thx
This question has been answered many times before, the following is for this specific case.
A Date object isn't required, the timestamp can be split into its parts, the month name converted to a number then the parts reformatted, e.g.
/*
mag 11, 2021 2:31:00 pm => DD/MM/YYYY HH:MM:ss
e.g. 11/05/2021 14:31
*/
function reformatDate(date) {
let z = n => ('0'+n).slice(-2);
let months = [,'gen','feb','mar','apr','mag','giu',
'lug','ago','set','ott','nov','dic'];
let [M,D,Y,h,m,s,ap] = date.toLowerCase().split(/\W+/);
h = h%12 + (ap == 'am'? 0 : 12);
M = months.indexOf(M);
return `${z(D)}/${z(M)}/${Y} ${z(h)}:${m}`;
}
console.log(reformatDate('mag 11, 2021 2:31:00 pm'));
In the OP, the format tokens include seconds but the example doesn't. Adding seconds to the above output if required should be easy.
The above can be modified to build the month names array based on a specific language, but then language to use would need to be passed to the function too.
If a library is used to parse the string, the language and format must be specified for the parser (e.g. date-fns allows setting the parse and format language), then the language and format of the output. So unless other date manipulation is required, a library may be more trouble than it's worth.
let now = new Date();
var dateString = moment(now).format('YYYY-MM-DD');
console.log(dateString) // Output: 2020-07-21
var dateStringWithTime = moment(now).format('YYYY-MM-DD HH:MM:SS');
console.log(dateStringWithTime) // Output: 2020-07-21 07:24:06
You can check here for all details of dateTime for Javascript
I have next code to take date:
var d = new Date();
var n = d.toString();
with output: Sun Oct 15 2017 12:09:42 GMT+0300 (EEST)
But I need to convert it to next format: 2017-10-15 12:09:42 +0300
Is that possible to do with Date class methods or I should use some regex for output string, to format it?
This can be done easily with a library called moment.js, please go through the docs for any additional tweaks, please check my below example and let me know if this helps you!
var moment_d = moment().format('YYYY-MM-DD hh:mm:ss ZZ');
console.log(moment_d);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
There is nothing in JavaScript's Date object that will conveniently get you the desired output. On the other hand, moment.js is a 80+ KB beast which is clearly an overkill in most situations.
There are some lightweight solutions out there if you look for them.
Alternatively you could parse the output of .toISOString(), which gets you as far as '2017-10-15T12:09:42.301Z', and combine it with .getTimezoneOffset() which returns the number of minutes from the UTC (positive towards West).
JS date-time manipulation libraries being large as they are, I recommend rolling your own if you only need to cover a few cases.
function formatDate(date) {
date = date || new Date(); // default to current time if parameter is not supplied
let formattedDate = date.toISOString(); // returns 2000-01-04T00:00:00.000Z
const timezone = date.getTimezoneOffset() / 0.6; // returns timezone in minutes, so dividing by 0.6 gives us e.g -100 for -1hr
const timezoneString = String(timezone) // padStart is a method on String
.padStart(4, '0') // add zeroes to the beginning if only 1 digits
.replace(/^(-|\+)(\d{3})$/, '$10$2') // add a zero between a - or + and the first digit if needed
.replace(/^\d/, '+$&'); // add a plus to the beginning if zero timezone difference
formattedDate = formattedDate
.replace('T', ' ') // replace the T with a space
.replace(/\.\d{3}Z/, '') // remove the Z and milliseconds
+ ' ' // add a space between timezone and time
+ timezoneString; // append timezone
return formattedDate;
}
console.log(formatDate(new Date(2016, 08, 24, 9, 20, 0)));
console.log(formatDate(new Date(2015, 03, 9, 18, 4, 30)));
console.log(formatDate(new Date(1999, 12, 4)));
console.log(formatDate(new Date(1999, 01, 4)));
console.log('----');
This works:
var myDateString = '19th sep 2015';
myDateString = myDateString.replace('st','');
myDateString = myDateString.replace('th','');
myDateString = myDateString.replace('nd','');
myDateString = myDateString.replace('rd','');
var date = new Date(myDateString);
But is there a cleaner way? Can I pass the date format (including the ordinal part) to the Date constuctor?
I wouldn't rely on it parsing correctly for all people - for instance, people in France might have their locale set to French (surprise) and that would fail to parse apr for instance, because for them it's avr.
Instead, parse it yourself:
var myDateString = '19th sep 2015';
var parts = myDateString.split(" ");
var date = parts[0].replace(/\D/g,''); // keep only numbers
var month = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(parts[1].toLowerCase())/3;
var year = parts[2];
var date = new Date(year, month, date);
// note because of how we got the month, it's already conveniently zero-based
Use Moment.js library and use your date string like this:
moment('19th sep 2015', 'Do MMMM YYYY').format("D MMMM YYYY")
Output:
"19 September 2015"
The easiest way is to use a library like moment.js or the date part of sugar.js.
To do this properly by hand is not fun.
Update
If you're in full control of the dates, just use ISO 8601 date format, which the constructor of Date understands in any browser.
I've seen a few questions about this, however none seem to be a universal solution for all browsers.
On my webpage I'm fetching a MYSQL Timestamp 'YYYY-MM-DD hh:mm:ss' in UTC. However, I need to convert this timestamp in Javascript to display just time in local meridian format... (i.e.. 8:00 pm).
The closest solution i found was appending 'UTC' to the MySQL timstamp string and creating a date object like that. However, this solution doesn't work in Safari. In anyone's knows of a solution please let me know.
Thank you in advance.
First convert MySql date string into JavaScript Date object. Then convert this gmt date object to local date object.
function mysqlGmtStrToJSDate(str) {
var t = str.split(/[- :]/);
// Apply each element to the Date function
return new Date(t[0], t[1]-1, t[2], t[3], t[4], t[5]);
}
function mysqlGmtStrToJSLocal(str) {
// first create str to Date object
var g = mysqlGmtStrToJSDate(str);
//
return new Date(g.getTime() - ( g.getTimezoneOffset() * 60000 ));
}
Converting the MySQL timestamp to Date object in JS and then using getTimezoneOffset() is a valid way to do it. According to the ECMAScript specification the Date should look something like this : YYYY-MM-DDTHH:MM:SS, so you should format the date correctly ( string replace(' ', 'T') )
If it is still not working, this is a list of date formats working across all browsers as described here
var d = new Date(2011, 01, 07);
var d = new Date(2011, 01, 07, 11, 05, 00);
var d = new Date("02/07/2011");
var d = new Date("02/07/2011 11:05:00");
var d = new Date(1297076700000);
var d = new Date("Mon Feb 07 2011 11:05:00 GMT");