How to convert a non local javascript date timezone to UTC? - javascript

How can I convert a date to UTC from a specific timezone?
In javascript you can convert a local date to utc and create a date from a date string or utc string.
The intl built in functions allow you to convert a datetime to a timezone, but not back to utc. I could not find any specific questions on this amazingly all others say local time.
I know that in moment you can convert a UTC from a timezone, like this:
var now = moment();
console.log(now.format('YYYY-MM-DD HH:mm:ss'))
console.log(now.utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").utc().format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").format('YYYY-MM-DD HH:mm:ss'))
console.log(now.tz("Australia/Sydney").tz("Asia/Tokyo").utc().format('YYYY-MM-DD HH:mm:ss'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.25/moment-timezone-with-data.min.js"></script>
The utcs should match. Aside from using moment, what other ways (browser, node, libraries) are there to convert a date considering it's in a timezone that is not local in the browser using js to utc? Doesn’t need to be vanilla js.

Here was my javascript native vanillajs solution using Intl.DateTimeFormat()
Basically I get the difference in the timezone specified and the local time. I add that difference then set return the utc.
/**
* take a date of assumed timezone and convert to utc
*
* #param {*} d
* #param {*} tz
* #returns
*/
function tzUTC(d, tz) {
// first calculate tz difference
// use passed in date to get timezone difference as close to that day.
var date = new Date(d);
var options = {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false,
timeZone: tz
};
var tzDate = new Intl.DateTimeFormat('en-US', options).format(date)
var diff = date - new Date(tzDate);
var minutes = Math.floor((diff / 1000) / 60);
var localTime = new Date(d);
localTime.setMinutes(d.getMinutes() + minutes);
return localTime.toUTCString();
}
var d = new Date("5/18/2019, 07:49:13");
// Fri May 17 2019 17:49:13 GMT-0400 (Eastern Daylight Time)
// utc should be Fri, 17 May 2019 21:49:13 GMT"
//
console.log("d:" + d)
console.log("tzUTC:" + tzUTC(d, 'Australia/Sydney'))
d = new Date("5/17/2019, 14:53:21");
console.log("d:" + d)
// Fri May 17 2019 17:53:21 GMT-0400 (Eastern Daylight Time)
// utc "Fri, 17 May 2019 21:53:21 GMT"
console.log("tzUTC:" + tzUTC(d, 'America/Los_Angeles'))

Related

How to convert string into date in js [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 1 year ago.
I have string like
Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)
How I can convert it into date
2021-06-07
Convert it into Date object and than into string?
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
console.log(date.getFullYear() + "-" + String(date.getMonth() + 1).padStart(2, 0) + "-" + String(date.getDay()).padStart(2, 0));
Date is represented as a standard with timestamp. You can't extract part if date and make its type as date. It would be string only. For formatting there are built in function like Intl. I am attaching here sample as well as link to Init documentation. You can explore more here Intl
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
options = {
year: 'numeric', month: 'numeric', day: 'numeric',
timeZone: 'America/Los_Angeles'
};
var d= new Intl.DateTimeFormat('en-US', options).format(date);
console.log(d);
Try this,
var date = new Date("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)");
const formatDate = date => [
date.getFullYear(),
(date.getMonth() + 1).toString().padStart(2, '0'),
date.getDate().toString().padStart(2, '0')
].join('-');
console.log(formatDate);
The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.
join('-') : adding '-' symbol between every elements(for concatenation)
getMonth()+1 - Since the month starts with 0, 1 is added.
Create Date object from string and then use toISOString() method to convert it to required format YYYY-mm-dd.
const convertDate = (dateStr) => {
const myDate = new Date(dateStr)
return myDate.toISOString().split("T")[0];
}
console.log(convertDate("Tue Jun 01 2021 09:55:41 GMT+0500 (Pakistan Standard Time)"));

Display Date (not time) from Firestore Timestamp

I'm pulling a timestamp from a Firestore database, and I only want to display the date to the user. The original timestamp is
Timestamp(seconds=1555477200, nanoseconds=0)
I've tried a few variations to get the Date, but they all have the same output-
Due: Wed Apr 17 2019 06:10:21 GMT-0500 (Central Daylight Time)
<p>Due: ${Date(dueDate)}<br>
<p>Due: <time>${Date(dueDate)}</time><br>
<p>Due: <time type="date">${Date(dueDate)}</time><br>
How do I cut off the time part of the timestamp?
(Ideally, I'd want "April 17, 2019", but if the day is in there that's fine too)
If you have a particular format for date, you can do
function getDate (timestamp=Date.now()) {
const date = new Date(timestamp);
let dd = date.getDate();
let mm = date.getMonth()+1; //January is 0!
const yyyy = date.getFullYear();
if(dd<10) {
dd = '0'+dd
}
if(mm<10) {
mm = '0'+mm
}
// Use any date format you like, I have used YYYY-MM-DD
return `${yyyy}-${mm}-${dd}`;
}
getDate(1555477200000);
// -> 2019-04-17
Alternatively, you can also do:
const time = new Date(1555477200000);
// -> Wed Apr 17 2019 10:30:00 GMT+0530 (India Standard Time)
const date = time.toDateString();
// -> Wed Apr 17 2019
P.S: I have used ES6 here. If you are working on ES5, use babel's online transpiler to convert.
Link: https://babeljs.io/repl
You can do
var time= timeStampFromFirestore.toDate();
console.log(time);
console.log(time.toDateString());
See the full documentation :
toDateString()
toDate()
You can use Date.toLocaleString() like this:
new Date(date).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' });
const timestamp = 1555477200000;
console.log(
new Date(timestamp).toLocaleString('en-EN', { year: 'numeric', month: 'long', day: 'numeric' })
);
Simply use moment.js and use your required format
date = moment();
console.log(date.format("MMMM D, YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.js"></script>

Convert Epoch time to human readable with specific timezone

To convert epoch dateTime to human readable , using a simple new date(1495159447834) will suffice.
The problem I'm encountering now is that for my hybrid application, if the user set the time-zone in his phone date time setting to lets say GMT +12:00 ,the human readable dateTime will be different from what I would want the user to have and I would want him/her to follow the server timezone.
Thus , how would I convert the epoch number to a specific given timezone in a human readable format.
I have tried example like:
var test= new Date('1495159447834 GMT+0800').toString();
and it returns me an Invalid Date.
If possible, I would want this without any libraries. I have looked through the answers here and I believe that I could not find any answers I'm looking for. If there is any previously answered question with the same topic, do let me know and I will close this question!
You can use offset to convert your current datetime to a specific timezone.
function convertEpochToSpecificTimezone(timeEpoch, offset){
var d = new Date(timeEpoch);
var utc = d.getTime() + (d.getTimezoneOffset() * 60000); //This converts to UTC 00:00
var nd = new Date(utc + (3600000*offset));
return nd.toLocaleString();
}
// convertEpochToSpecificTimezone(1495159447834, +3)
The offset will be your specific timezone. Example: GMT +03:00, your offset is +3. If GMT -10:00, offset is -10
there are number of ways to convert between Epoch and Human readable format
//Convert epoch to human readable date
var myDate = new Date( 1533132667*1000);
document.write(myDate.toGMTString()+"<hr>"+myDate.toLocaleString());
//this will return Wed, 01 Aug 2018 14:11:07 GMT
//Convert human readable dates to epoch
var myDate = new Date("Wed Aug 01 2018 14:11:07 GMT");
var myEpoch = myDate.getTime()/1000.0;
// this will return 1533132667
For Reference: https://www.epochconverter.com/programming/#javascript
Edit#
added a JSFiddle here
This is old, but I did it this way:
function formatDate(date, includeTime) {
const dateTimeFormat = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
timeZone: 'America/Los_Angeles',
timeZoneName: 'short',
});
const [
{ value: month },
,
{ value: day },
,
{ value: year },
,
{ value: hour },
,
{ value: minute },
,
{ value: dayPeriod },
,
{ value: timeZoneName },
] = dateTimeFormat.formatToParts(date);
if (includeTime) {
return `${day} ${month} ${year} • ${hour}:${minute}${dayPeriod.toLowerCase()} ${timeZoneName}`;
}
return `${day} ${month} ${year}`;
This will output the time of the given timezone.
For example, if I have an epoch time (unix timestamp) and if I'm in Argentina, the time should be displayed as 03:45 GMT -3 of June 2, but with this code, it will be displayed as the time that should be displayed for Los Angeles.
My requirement was to display time in Los Angeles timezone, even if I visit the page from Argentina.
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);
Or you can use momentjs
moment.unix(yourUnixEpochTime).format('dddd, MMMM Do, YYYY h:mm:ss A')
or you can use this way
var dateVal ="/Date(1342709595000)/";
var date = new Date(parseFloat(dateVal.substr(6)));
document.write(
(date.getMonth() + 1) + "/" +
date.getDate() + "/" +
date.getFullYear() + " " +
date.getHours() + ":" +
date.getMinutes() + ":" +
date.getSeconds()
);

how to convert date into utc milliseconds with timezone in javascript

getTime() Is it return local or UTC milliseconds?
var startDate = new Date();
var val = (startDate.getTime()).toString();
Below logic will return UTC millisecords:
var startDate = new Date();
var val = (new Date(Date.UTC(
startDate.getFullYear(),
startDate.getMonth(),
startDate.getDate(),
startDate.getHours(),
startDate.getMinutes(),
startDate.getSeconds()
))).getTime().toString();
Need script for converting the date to UTC milliseconds with timezone like America/Los_Angeles
Here you create a new date:
var startDate = new Date();
This is set to your browsers current timezone, here mine is Turkey:
Fri Sep 02 2016 17:50:06 GMT+0300 (Turkish Summer Time)
If you convert this string Fri Sep 02 2016 17:50:06 GMT+0300 into millis then you will have the value with the GMT+0300:
Date.parse("Fri Sep 02 2016 17:50:06 GMT+0300")
>> 1472827806000
Here, you can create your date object with a different timezone and get the millis of it, let's say it is America/Los_Angeles:
1) Create date object
var d = new Date();
2) Get the local time value
var localTime = d.getTime();
3) Get the local offset
var localOffset = d.getTimezoneOffset() * 60000;
4) Obtain UTC
var utc = localTime + localOffset;
5) Obtain the destination's offset, for America/Loas_Angeles it is UTC -7
var offset = -7;
var ala = utc + (3600000*offset);
6) Now ala contains the milis value of America/Los_Angeles. Finally convert it to a new date object if needed:
var nd = new Date(ala);
Final: Now you can get the miliseconds of the new date object:
nd.getTime();
//or
ala;

Getting current time from the date object

function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0].substring(2), // get only two digits
month = datePart[1], day = datePart[2];
document.write(new Date(day+'/'+month+'/'+year));
}
formatDate ('2010/01/18');
When i print this i get Thu Jun 01 1911 00:00:00 GMT+0530 (India Standard Time) but the system is actually 3:42 P.M
Use the current date to retrieve the time and include that in the new date. For example:
var now = new Date,
timenow = [now.getHours(),now.getMinutes(),now.getSeconds()].join(':'),
dat = new Date('2011/11/30 '+timenow);
you must give the time:
//Fri Nov 11 2011 00:00:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11"));
//Fri Nov 11 2011 23:23:00 GMT+0800 (中国标准时间)
alert(new Date("11/11/11 23:23"));
What do you want? Just the time? Or do you want to define a format? Cu's the code expects this format for date: dd/mm/yyyy, changed this to yyyy/mm/dd
Try this:
function formatDate (input) {
var datePart = input.match(/\d+/g),
year = datePart[0],
month = datePart[1], day = datePart[2],
now = new Date;
document.write(new Date(year+'/'+month+'/'+day+" " + now.getHours() +':'+now.getMinutes() +':'+now.getSeconds()));
}
formatDate ('2010/01/18')
Output:
Mon Jan 18 2010 11:26:21 GMT+0100
Passing a string to the Date constructor is unnecessarily complicated. Just pass the values in as follows:
new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10))
You're creating a Date() object with no time specified, so it's coming out as midnight. if you want to add the current date and time, create a new Date with no arguments and borrow the time from it:
var now = new Date();
var myDate = new Date(parseInt(year, 10), parseInt(month, 10), parseInt(day, 10),
now.getHours(), now.getMinutes(), now.getSeconds())
No need to strip the last two characters off the year. "2010" is a perfectly good year.

Categories

Resources