Convert date string into another string format - javascript

I have the date in this format:
Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
I want this string to be converted into this format:
2016-11-15 00:00:00
I tried:
var s = startDate.format('YYYY-MM-DD HH:mm:ss');

I would recommend using the library moment.js. This library was specifically designed to help with dates and formatting.
You simply need to do this:
let date = moment('Tue Nov 15 2016 00:00:00 GMT+0800').format('YYYY-MM-DD HH:mm:ss')
console.log(date)
However, there is a caveat. Since the date that you are providing is in a nonstandard format, you will get a deprecation warning, like this:
Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Basically, the solution is to provide a standard format for your date. The simplest way to do that is to either chop off the timezone, since it seems like you will be displaying the date assuming the TZ supplied is the local one.

You can get it done just using vanilla javascript:
const date = new Date('Tue Nov 15 2016 00:00:00 GMT+0800 (Malay Peninsula Standard Time');
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
const hours = date.getHours();
const minutes = date.getMinutes();
const seconds = date.getSeconds();
const timeToHHMMSS = (hours, minutes, seconds) => {
return [hours, minutes, seconds].map(value => {
return ('0' + value).slice(-2);
}).join(':');
}
const formattedDate = `${year}-${month}-${day}`;
const formattedTime = timeToHHMMSS(hours, minutes, seconds);
console.log(`${formattedDate} ${formattedTime}`);

Related

DayJS: Format and Convert an ISO Date/Time String to Local Timezone's Date/Time

I'm consuming an API which returns timestamps in this format 2023-02-18T14:54:28.555Z which is an ISO string. I need to format this value to the timezone of the user.
I've tried this:
dayjs("2023-02-18T14:54:28.555Z").format('YYYY-MM-DD HH:MM:ss A') // => "2023-02-18 20:02:28 PM"
The above output is incorrect and is 30 minutes behind for +0530 IST Timezone.
But when I input the same string "2023-02-18T14:54:28.555Z" to the JavaScript date constructor, I can see the correct value.
new Date("2023-02-18T14:54:28.555Z").toString() // => 'Sat Feb 18 2023 20:24:28 GMT+0530 (India Standard Time)'
How to get the correct formatted value for my Timezone using DayJS?
Tried feeding the ISO string to the DayJS constructor and expected it'll parse it to the current timezone. But the output value is 30 minutes behind.
you can use toLocaleString() method:
const timestamp = "2023-02-18T14:54:28.555Z";
const date = new Date(timestamp);
const options = { timeZone: 'Asia/Kolkata' };
const formattedDate = date.toLocaleString('en-US', options);
console.log(formattedDate);
Date.toString() displays the Date according to the local time of the OS. If you need the time to display in a zone other than the local time of the OS, then you'll have to use the DayJS Timezone plugin.
const dayjs = require('dayjs');
const utc = require('dayjs/plugin/utc');
const timezone = require('dayjs/plugin/timezone');
const timestamp = '2023-02-18T14:54:28.555Z';
dayjs.extend(utc);
dayjs.extend(timezone);
// Seattle time because my OS is set to America/Los_Angeles time.
const seattleString = Date(timestamp).toString();
const dayjsLocal = dayjs(timestamp);
const dayjsIst = dayjsLocal.tz('Asia/Calcutta');
const istString = dayjsIst.format('YYYY-MM-DDTHH:mm:ss');
console.log(seattleString); // Sun Feb 19 2023 02:43:42 GMT-0800 (Pacific Standard Time)
console.log(istString); // 2023-02-18T20:24:28

how to convert date to 20160422060933.0Z format?

In angular I have to save data to database in this time format 20160422060933.0Z ?
Someone told me that this is Microsoft time format. I don't know how to convert date to this format, anyone encountered this before?
2016 is a year, 04 is a month, and 22 is a date but i don't know what 060933.0Z is. We use Dreamfactory API and SQL Server
Later edit: based on another answer, actually this seems to be a standard format colloquially called a "LDAP date". See Converting a ldap date for some details on the format (and how to parse it in Java). It can for sure be easily parsed with any typical JS date library or even without any library.
Let's break it down into pieces.
2016 = full year
04 = month, padded to 2 digits
22 = day of month, likely also padded to 2 digits
06 = hour of day, padded to 2 digits, likely on a 24h scale
09 = minute of the hour, padded to 2 digits
33 = second of the minute, likely padded to 2 digits
. = literal
0 = probably "second fraction"
Z = offset from UTC. Z meaning UTC.
Parsing it
You have several options to parse it:
If you assume you're going to always get an UTC datetime from the backend, you can naively parse it in JavaScript just by extracting the relevant substrings.
const input = '20160422060933.0Z';
new Date(Date.UTC(
input.substr(0, 4), // year
input.substr(4, 2) - 1, // month is 0-indexed
input.substr(6, 2), // day
input.substr(8, 2), // hour
input.substr(10, 2), // minute
input.substr(12, 2), // second
("0." + input.split(/[.Z]/gi)[1]) * 1000 // ms
));
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
You can be a little creative and actually manipulate the string into an ISO format. Then you can just use the native Date.parse function, which supports parsing ISO strings (other formats are browser-dependent). The advantage is that it'll support dates that are not UTC as well.
new Date(Date.parse(
input.substr(0, 4) + "-" + // year, followed by minus
input.substr(4, 2) + "-" + // month, followed by minus
input.substr(6, 2) + "T" + // day, followed by minus
input.substr(8, 2) + ":" + // hour, followed by color
input.substr(10, 2) + ":" + // minute, followed by color
input.substr(12, 2) + // second
input.substr(14) // the rest of the string, which would include the fraction and offset.
))
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
Use a library like luxon, momentjs, etc. This you might already have a JS library in your project. You'd need to build a date format pattern to parse this format into a native Date object or some other library-specific object. For example, with momentjs you'd do:
moment("20160422060933.0Z", "YYYYMMDDHHmmss.SZ")
// Fri Apr 22 2016 09:09:33 GMT+0300 (Eastern European Summer Time)
Formatting into it
This side of the operation is even simpler.
Without any date library, you just need to get rid of the "-", ":" and "T" separators from the ISO format. So you can just do the following:
new Date().toISOString().replace(/[:T-]/g, "")
// '20230209175305.421Z'
If you want to use a date library, then you just do the reverse, format operation using the same pattern as for parsing. Eg. in momentjs:
moment(new Date()).utc().format("YYYYMMDDHHmmss.S[Z]")
// "20230209175222.5Z"
(note that I needed to place the "Z" in brackets due to https://github.com/moment/moment-timezone/issues/213).
Just a side note to the other answer here:
You can use ldap2date npm package for parsing, should be not that "heavy" as moment.
Code:
import ldap2date from "ldap2date";
// or import { parse, toGeneralizedTime } from "ldap2date";
const dateString = "20160422060933.0Z";
const date = ldap2date.parse(dateString);
console.log(date.toUTCString());
// Fri, 22 Apr 2016 06:09:33 GMT
const str = ldap2date.toGeneralizedTime(date);
console.log(str);
// 20160422060933Z (note: no period.)
console.log(str.replace("Z", ".0Z"));
// 20160422060933.0Z
function getLdapString(date) {
return ldap2date.toGeneralizedTime(date);
}
const d = new Date();
console.log(getLdapString(d), d.toISOString());
// 20230209181603.965Z 2023-02-09T18:16:03.965Z
And some monkey-patching to match "format":
function getLdapString(date) {
return date.getMilliseconds() !== 0
? ldap2date.toGeneralizedTime(date)
: ldap2date.toGeneralizedTime(date).replace("Z", ".0Z");
}
const d = new Date();
d.setMilliseconds(15);
const d1 = new Date();
d1.setMilliseconds(0);
console.log("Date with milliseconds: ", d.toUTCString(), getLdapString(d));
console.log("Date without milliseconds: ", d1.toUTCString(), getLdapString(d1));
// Date with milliseconds: Thu, 09 Feb 2023 18:22:27 GMT 20230209182227.15Z
// Date without milliseconds: Thu, 09 Feb 2023 18:22:27 GMT 20230209182227.0Z
Or to ignore milliseconds part completelly
function getLdapString(date) {
const copy = new Date(date);
copy.setMilliseconds(0);
return ldap2date.toGeneralizedTime(copy).replace("Z", ".0Z");
}
console.log("Date with milliseconds: ", d.toUTCString(), getLdapString(d));
console.log("Date without milliseconds: ", d1.toUTCString(), getLdapString(d1));
// Date with milliseconds: Thu, 09 Feb 2023 18:29:50 GMT 20230209182950.0Z
// Date without milliseconds: Thu, 09 Feb 2023 18:29:50 GMT 20230209182950.0Z

How to convert a Date object to output only hh:mm am/pm

I am attempting to convert the following into a 12 hour am/pm format.
Currently I am recieving the Day, Month, Year and timezone.
Fixed by adding .toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.)/, "$1$3")*
<div id="time1"></div>
<div id="time2"></div>
var date = new Date('08/16/2019 12:00:00 PM UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time1").innerHTML = date;
var date = new Date('08/16/2019 6:00:00 am UTC').toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
document.getElementById("time2").innerHTML = date;
Basically what you have to do is use the Date() default javascript function and make sure you append the UTC timezone:
var date = new Date('08/16/2019 7:00:00 PM UTC')
date.toString=() //will then print out the timezone adjusted time
"Fri Aug 16 2019 22:00:00 GMT+0300 (Eastern European Summer Time)"
There are many built in javascript methods to handle converting date objects. This example will look to the browser to determine date format and time.
let time = Date.now();
time.toLocaleDateString();

UTC date convert to local timezone

I have a date in UTC format.
"2016-10-12 05:03:51"
I made a function to convert UTC date to my local time.
function FormatDate(date)
{
var arr = date.split(/[- :T]/), // from your example var date = "2012-11-14T06:57:36+0000";
date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], 00);
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;
}
My Local timezone is GMT +0530.
My code produced this output:
Tue Oct 11 2016 10:33:00 GMT+0530 (IST)
I converted the date with an online tool to get the correct date and time.
Wednesday, October 12, 2016 10:30 AM
My code matches the online tool on time but not on date.
How can I correct my code's output, preferably using moment.js?
UTC is a standard, not a format. I assume you mean your strings use a zero offset, i.e. "2016-10-12 05:03:51" is "2016-10-12 05:03:51+0000"
You are on the right track when parsing the string, but you can use UTC methods to to stop the host from adjusting the values for the system offset when creating the date.
function parseDateUTC(s){
var arr = s.split(/\D/);
return new Date(Date.UTC(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]));
}
console.log(parseDateUTC('2016-10-12 05:03:51').toLocaleString());
If you want to use moment.js, you can do something like the following. It forces moment to use UTC when parsing the string, then local to write it to output:
var d = moment.utc('2016-10-12 05:03:51','YYYY-MM-DD HH:mm:ss');
console.log(d.local().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.0/moment.js"></script>
Since you have tagged moment, I'm assuming you are using moment.
In such cases, you should keep your approach consistent and not mix moment and date object.
var dateStr = '2016-10-12 05:03:51';
var timeZone = "+0530";
var date = moment.utc(dateStr).utcOffset(dateStr + timeZone)
console.log(date.toString())

Convert UTC date time to local date time

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

Categories

Resources