Setting Time input format in Frontend - javascript

I'm trying to modify the below code in React Typescript. I want to return the input value in time format like - "Thu Jan 01 2022 13:03:00 GMT-0500 (Eastern Standard Time)" any suggestions how to do it?
Full Code: https://codepen.io/dcode-software/pen/jOwVqGO
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
return `${selects.hour.value}:${selects.minute.value} ${selects.meridiem.value}`;
}
function numberToOption(number) {
const padded = number.toString().padStart(2, "0");
return `<option value="${padded}">${padded}</option>`;
}
activate();

You can create a new Date object and set the hours and minutes on it. From there you get convert it to a string. Like this:
function getTimeStringFromPicker(timePicker) {
const selects = getSelectsFromPicker(timePicker);
const d = new Date();
d.setMinutes(selects.minute.value);
// setHours takes in hours in 24hr format
if (selects.meridiem.value === "pm") {
d.setHours(selects.hour.value + 12);
} else {
d.setHours(selects.hour.value);
}
return d.toString();
}

If you can reach a Date object somehow, its toLocaleString() method can do something like that (the actual parameters are described here.
let date = new Date();
console.log(date.toLocaleString("en-US", {
timeZone: "EST",
dateStyle: 'full',
timeStyle: 'full',
hour12: false // this is because you seem to want a 24-hour format
}));
If you need more, moment.js might be a library to check.

Related

Display and Formatting UTC Time On Static Website in Real-Time

My website currently displays UTC time like this:
2022-03-22T23:38:25.748Z
But I would like for it to be formatted like this:
23:39:22 UTC
Here is the javascript I have:
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var x = new Date()
var x1=x.toISOString();// changing the display to UTC string
document.getElementById('ct').innerHTML = x1;
tt=display_c();
}
<body onload=display_ct();><span id='ct' >
Can you help me format this? I've looked into using angular and searched other methods for implementing this but it seems that there are many ways to do this. The things I've tried do not display the format correctly. The code above is the closest solution I have found.
This should produce the format you want to have.
let date = new Date();
let utc_string = date.toUTCString().match(/..:..:.. .*/)[0];
console.log(utc_string);
new Date().toISOString().slice(11, 19) + ' UTC'
A nice and intentional property of the ISO datetime format is that most of the parts are always the same length.
Note that truncating, not rounding, is the correct behavior.
Use the Intl.DateTimeFormat method for this as follows:
function display_c(){
const refresh = 1000;
mytime = setTimeout('display_ct()',refresh)
}
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "long" });
document.getElementById('ct').innerHTML = dtf.format( new Date() );
tt = display_c();
}
display_ct();
<div id="ct"></div>
Customization:
You can either use the various configuration options available to customize the format of the datetime, or use the following setup for displaying a custom String:
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "medium" });
document.getElementById('ct').innerHTML = dtf.format( new Date() ) + " Zulu";
}
Available configuration options: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
I found a web to helping you. And i give an example to you too.
https://www.codevscolor.com/javascript-iso-utc
const date = new Date('2022-03-22T23:38:25.748Z')
console.log(date.toString())
console.log(date.toUTCString())

How can I create a list of days between 2 dates? [duplicate]

I have two moment dates:
var fromDate = moment(new Date('1/1/2014'));
var toDate = moment(new Date('6/1/2014'));
Does moment provide a way to enumerate all of the dates between these two dates?
If not, is there any better solution other than to make a loop which increments the fromDate by 1 until it reaches the toDate?
Edit: Adding date enumeration method and problem
I've mocked up a method for enumerating the days between two dates, but I'm running into an issue.
var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];
startDate = startDate.add(1, 'days');
while(startDate.format('M/D/YYYY') !== endDate.format('M/D/YYYY')) {
console.log(startDate.toDate());
dates.push(startDate.toDate());
startDate = startDate.add(1, 'days');
}
return dates;
};
Take a look at the output when I run enumerateDaysBetweenDates( moment(new Date('1/1/2014')), moment(new Date('1/5/2014'));
Thu Jan 02 2014 00:00:00 GMT-0800 (PST)
Fri Jan 03 2014 00:00:00 GMT-0800 (PST)
Sat Jan 04 2014 00:00:00 GMT-0800 (PST)
[ Sun Jan 05 2014 00:00:00 GMT-0800 (PST),
Sun Jan 05 2014 00:00:00 GMT-0800 (PST),
Sun Jan 05 2014 00:00:00 GMT-0800 (PST) ]
It's console.logging the right dates, but only the final date is being added to the array. How/why is this? This smells like some sort of variable reference issue - but I'm not seeing it.
.add() is a mutator method, so the assignment in this line is unnecessary:
startDate = startDate.add(1, 'days');
You can just do this, and have the same effect:
startDate.add(1, 'days');
While it's name would imply the creation of a new Date object, the toDate() method really just returns the existing internal Date object.
So, none of your method calls are creating new Date or moment object instances. Fix that by using .clone() to get a new instance:
startDate = startDate.clone().add(1, 'days');
Or better yet, wrap the values in a call to moment() as Mtz suggests in a comment, and it will clone the instance, if the value is a moment object, or it will parse the input to create a new moment instance.
startDate = moment(startDate).add(1, 'days');
I think a date enumerator method should not change either of the arguments passed in. I'd create a separate variable for enumerating. I'd also compare the dates directly, rather than comparing strings:
var enumerateDaysBetweenDates = function(startDate, endDate) {
var dates = [];
var currDate = moment(startDate).startOf('day');
var lastDate = moment(endDate).startOf('day');
while(currDate.add(1, 'days').diff(lastDate) < 0) {
console.log(currDate.toDate());
dates.push(currDate.clone().toDate());
}
return dates;
};
Got it for you:
var enumerateDaysBetweenDates = function(startDate, endDate) {
var now = startDate.clone(), dates = [];
while (now.isSameOrBefore(endDate)) {
dates.push(now.format('M/D/YYYY'));
now.add(1, 'days');
}
return dates;
};
Referencing now rather than startDate made all the difference.
If you're not after an inclusive search then change .isSameOrBefore to .isBefore
Fiddle: http://jsfiddle.net/KyleMuir/sRE76/118/
use moment and work with while loop, code will run in loop untill startDate is equal to endDate and push startDate and then increment it with 1 day so can get next date
function enumerateDaysBetweenDates (startDate, endDate){
let date = []
while(moment(startDate) <= moment(endDate)){
date.push(startDate);
startDate = moment(startDate).add(1, 'days').format("YYYY-MM-DD");
}
return date;
}
you can test it by calling function like this
let dateArr = enumerateDaysBetweenDates('2019-01-01', '2019-01-10');
Using moment library and for loop you can enumerate between two dates.
let startDate = moment('2020-06-21');
let endDate = moment('2020-07-15');
let date = [];
for (var m = moment(startDate); m.isBefore(endDate); m.add(1, 'days')) {
date.push(m.format('YYYY-MM-DD'));
}
console.log(date)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Momentjs doesn't provide this by itself but there is a plugin which offers it: moment-range.
Specifically, check out the Iteration docs.
As an extension of Kyle's answer - I've been trying to get this to work with Unix timestamps and after lots of trial and error I got it to work and thought I'd post it here in case anyone is seeking the same thing and needs it. See my code below:
fromDate = moment.unix(req.params.dateFrom).format('YYYY-MM-DD')
toDate = moment.unix(req.params.dateTo).format('YYYY-MM-DD')
// Returns an array of dates between the two dates
function enumerateDaysBetweenDates(startDate, endDate) {
startDate = moment(startDate);
endDate = moment(endDate);
var now = startDate, dates = [];
while (now.isBefore(endDate) || now.isSame(endDate)) {
dates.push(now.format('YYYY-MM-DD'));
now.add(1, 'days');
}
return dates;
};
Note that I convert it to Unix, then convert that value to moment again. This was the issue that I had, you need to make it a moment value again in order for this to work.
Example usage:
fromDate = '2017/03/11' // AFTER conversion from Unix
toDate = '2017/03/13' // AFTER conversion from Unix
console.log(enumerateDaysBetweenDates(fromDate, toDate));
Will return:
['2017/03/11', '2017/03/12', '2017/03/13']
Using ES6 notation
const from = moment('01/01/2014', 'DD/MM/YYYY')
const to = moment('06/01/2014', 'DD/MM/YYYY')
const nbDays = to.diff(from, 'days') + 1
const result = [...Array(nbDays).keys()]
.map(i => from.clone().add(i, 'd'))
console.log(result)
<script src="https://momentjs.com/downloads/moment.min.js"></script>
You can easily enumerate with moment.js Here is a more generic solution for days, weeks, months or years:
https://gist.github.com/gvko/76f0d7b4b61b18fabfe9c0cc24fc3d2a
Using moment library and for loop you can enumerate between two dates.
const moment = require('moment');
let startDate = moment('2021-12-24');
let endDate = moment('2022-1-4');
let date = [];
for (var m = moment(startDate); m.isSameOrBefore(endDate); m.add(1, 'days')) {
date.push(m.format('DD/MM/YYYY'));
}
console.log(date)

How to format full local date into simple mm/dd/yyyy? [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
Need to format this date:
[Wed Jul 03 2019 00:00:00 GMT+0200 (Central European Summer Time),
Thu Aug 01 2019 23:59:59 GMT+0200 (Central European Summer Time)]
Into simple mm/dd/yyyy, but not with moment. Cus moment is to heavy.
This is my format function which get array date = [startDate, endDate]
formatDate = (date) => {
const newDate = new Date(date);
const dateFormatted = [];
for (let i = 0; i < date.length; i++) {
dateFormatted[i] = `${newDate.getMonth() + 1}/${newDate.getDate()}/${newDate.getFullYear()}`;
}
return dateFormatted;
};
As result I am getting this NaN/NaN/NaN
Any suggestion, advice?
I recommend you to not customize your Date variables it in that way,
You should define your LOCALE_ID which means that you don't need to use custom format for your Date (or currency, time etc.) variables. For example,
import { LOCALE_ID } from '#angular/core';
import { platformBrowserDynamic } from '#angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule, {
providers: [{provide: LOCALE_ID, useValue: 'en-US' }]
});
Source: https://angular.io/api/core/LOCALE_ID#description
So, the result you want is something like:
`${d.getMonth().toString().padStart(2,'0')}/${d.getDate().toString().padStart(2,'0')}/${d.getFullYear()}`
So your function should be:
let formatDate = (date) => {
let d = new Date(date)
return `${d.getMonth().toString().padStart(2,'0')}/${d.getDate().toString().padStart(2,'0')}/${d.getFullYear()}`;
}
and then you can call it on a list of dates.
let dateList = [new Date(), new Date()]
formattedDates = dateList.map(formatDate)
You can also extend this to take a list of dates to process.
let formatDates = (dates) => dates.map(formatDate);
so you can also pass in a list of dates to process, leveraging the singular formatDate
Simple js function to convert Date object to string:
const date = new Date();
function tommddyyyy(date) {
return `${date.getMonth() + 1}/${date.getDate()}/${date.getFullYear()}`;
}
console.log(tommddyyyy(date));
The posted code doesn't produce NaN/NaN/NaN, it formats the date as m/d/y.
Your problem is here:
for (let i = 0; i < date.length; i++)
The value of date is a string like "Wed Jul 03 2019 00:00:00 GMT+0200" with length 33, so you get 33 formatted dates. There are already many questions on parsing and formatting dates, so I'll mark this as a duplicate of those.
angular has it's own formatDate function, I'd recommend using it:
import {formatDate} from '#angular/core';
formatDate(date, 'short', 'en-US');
1st arg is date or string, second is format (or shorthand format as used here), 3rd is the locale.
I expect date_arr to be an array of strings parsable as dates. Then I would use this plain javascript solution:
formatDate = (date_arr) => {
return date_arr.map( dt => {
// create an date object and convert to an iso-string (yyyy-mm-dd)
var iso = new Date(dt).toISOString().substr(0,10);
// rearrange the values as needed (mm-dd-yyyy)
iso = `${iso.substr(5)}-${iso.substr(0,4)}`;
// replace delimiter '-' with '/'
return iso.replace(/-/g, '/');}
);
};
// sample call
formatDate(['2019-05-03', new Date()]);
// ["05/03/2019", "07/18/2019"]

JS: new Date() is not accepting date string in my own locale (d/m/y)

My browser (ie. my OS) should know I'm in Australia and what the correct date format is. In this case, d/m/y, not m/d/y. However if I run the following code:
alert(new Date("21/11/1968"))
The result is "Thu Sep 11 1969". It is thinking the month comes first and adjusting accordingly.
Why is this? Is the answer to always use a universal format as input to date functions, or is there a way to tell the browser to expect dates input in my locale format?
It's pretty simple to convert your date string to a format that will give the expected result ('yyyy/mm/dd' or 'yyyy-mm-dd'):
new Date("21/11/1968".split('/').reverse().join('/'));
[edit] You may like this more generic method (part of the npm PureHelpers library):
document.querySelector("#result").textContent = `
tryParseDate("2017/03/22", "ymd"); // ${tryParseDate("2017/03/22", "ymd")}
tryParseDate("03/22/2017", "mdy"); // ${tryParseDate("03/22/2017", "mdy")}
tryParseDate("22-03-2017", "dmy"); // ${tryParseDate("22-03-2017", "dmy")}
`;
function tryParseDate(dateStringCandidateValue, format = "dmy") {
if (!dateStringCandidateValue) {
return null;
}
const mapFormat = format.split("").reduce(function(a, b, i) {
a[b] = i;
return a;
}, {});
const dateStr2Array = dateStringCandidateValue.split(/[ :\-\/]/g);
const datePart = dateStr2Array.slice(0, 3);
const datePartFormatted = [
+datePart[mapFormat.y],
+datePart[mapFormat.m] - 1,
+datePart[mapFormat.d]
];
if (dateStr2Array.length > 3) {
dateStr2Array.slice(3).forEach(t => datePartFormatted.push(+t));
}
const dateTrial = new Date(Date.UTC.apply(null, datePartFormatted));
return dateTrial && dateTrial.getFullYear() === datePartFormatted[0] &&
dateTrial.getMonth() === datePartFormatted[1] &&
dateTrial.getDate() === datePartFormatted[2]
? dateTrial
: null;
}
<pre id="result"></pre>
The Date object is very weak. You cannot tell it what format to expect. You can create it with a string in m/d/y like you stated, or new Date(year, month, day[, hours, seconds, milliseconds]);
new Date(string_date) supports the following Date formats:
MM-dd-yyyy
yyyy/MM/dd
MM/dd/yyyy
MMMM dd, yyyy
MMM dd, yyyy
You need to parse it using a new date object like
const myDate = new Date('Wed Dec 30 2020 00:00:00 GMT-0500 (Eastern Standard Time)')
Then convert it:
const dateFormatted = myDate.toLocaleDateString("en-US")

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