Convert UTC to current timezone in javascript - javascript

I have time as 2023-02-01T17:00:22.127Z which is in UTC. I want to convert this to the timezone of the user from where user is logged in. How can I do this using javascript?
I was trying to use https://yarnpkg.com/package/jstz but couldn’t use a way to convert the time. Please help resolve this issue

Here is a function that converts a UTC date string to a local browser date string with format YYYY-MM-DD hh:MM:
function getLocalDateString(utcStr) {
const date = new Date(utcStr);
return date.getFullYear()
+ '-' + String(date.getMonth() + 1).padStart(2, '0')
+ '-' + String(date.getDate()).padStart(2, '0')
+ ' ' + String(date.getHours()).padStart(2, '0')
+ ':' + String(date.getMinutes()).padStart(2, '0');
}
console.log({
'2023-02-01T00:55:22.127Z': getLocalDateString('2023-02-01T00:55:22.127Z'),
'2023-02-01T17:00:22.127Z': getLocalDateString('2023-02-01T17:00:22.127Z')
});
Ouput in my timezone:
{
"2023-02-01T00:55:22.127Z": "2023-01-31 16:55",
"2023-02-01T17:00:22.127Z": "2023-02-01 09:00"
}

Related

Convert stringDate to new Date() and back again in same format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I've got multiple dictionaries with dates in and I need to find the highest one. To compare the dates I get the date from the dictionary, convert it using new Date(dateString) to be able to compare the dates to get the latest date.
The dateString looks like this: 2019-03-07 08:40:16
I convert this using new Date(dateString) and it looks like this:
Thu Mar 07 2019 08:40:16 GMT+0000 (Greenwich Mean Time)
I then need to convert it back to original format YYYY-MM-DD HH:MM:SS
What is the best way to do this, I thought there would be something where you could define the output format for new Date() but can't find anything.
Any help is appreciated.
I'd recommend you to use Moment https://momentjs.com/ lib for time comparison and formatting.
const date1 = moment('2019-03-06 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const date2 = moment('2019-03-07 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const isBefore = date1.isBefore(date2);
console.log('isBefore', isBefore);
console.log('formatted date:', date2.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
This is surely ain't the most elegant solution but based on the conversion from dateString, you can reconstruct it using the Date() objects built-in methods.
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
var temp2 = "" + temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate() + " " + temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds();
console.log(temp2);
If you plan to do this with multiple dates, you might consider enhancing the Date object with your own method like:
Date.prototype.reformat = function() {
return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + "." + this.getSeconds();
}
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
console.log(temp.reformat());

Display the date to the user in different Dateformat depending where he is from

I got a function which converts my timestamp into a date and looks like this:
delivery: function(created) {
var date = new Date(created * 1000);
var formattedDate = ('0' + date.getDate()).slice(-2) + '/' +
('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear() + ' ,' +
('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
return formattedDate;
}
now I want to display the date in MM/DD/YYYY for the american user which come to my site, so I would like to implement an if-clause, which firstly looks where the user comes from and then display the date in MM/DD/YYYY if he is from america, and if he is from europe in DD/MM/YYYY
Well in the SAPUI5 documentation I just saw this:
// The source value is given as timestamp. The used output pattern is "dd.MM.yyyy HH:mm": e.g. 22.12.2010 13:15
oType = new sap.ui.model.type.DateTime({source: {pattern: "timestamp"}, pattern: "dd.MMM.yyyy HH:mm"});
but I don't really understand how it works if I do oType.formatValue(created); its not working so maybe someone with more experience can explain me where I have to put my timestamp which is stored under "created"
What's wrong with simply using
delivery: function(created) {
var date = new Date(created * 1000);
return date.toLocaleDateString() + " " + date.toLocaleTimeString();
}
exactly?
EDIT: For clarity, I've supplied the whole function, not just the return statement

Get current date in this format [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 6 years ago.
How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?
I would like to know if there is a function or method for this. I am not asking how to convert a string into another.
To be precise: .toISOString().slice(0, -5)
var d1 = new Date()
var str = d1.toISOString().slice(0, -5)
console.log(str);
How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?
That seems to be an ISO 8601 format date without a timezone, which will be treated as a "local" time. There is a built—in toISOString method, but it always uses UTC.
So you can either write your own function (fairly trivial, see below) or use a library (really not required if you just want to format a date string).
I would like to know if there is a function or method for this.
Not a built–in function, no.
/* Return an ISO 8601 string without timezone
** #param {Date} d - date to create string for
** #returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
function z(n){return (n<10?'0':'') + n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' + z(d.getSeconds())
}
document.write(toISOStringLocal(new Date()));
Use moment.js It will blow your mind. Add this script to you HTML
<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-locales.js"></script>
And use this code:
var date=moment().format('YYYY-MM-DDTHH:mm:ss');
Try this function:
function(d) {
var cad = "";
try{
cad = d.getUTCFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getHours())
+ ":" + pad(d.getUTCMinutes()) + ":" + pad( d.getSeconds()) ;
return cad;
}catch(e){
return null;
}
}

User current time

I have a script that stores an action taken by a user. There's a column that contains datetime and originally I user NOW(), but that uses server time, which is a few hours off as compared to the user's actual time.
So I decided I'll use the time that I can get with JS. I've formatted it this way:
var now = new Date(),
isnow = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2) + ' ' + ('0' + (now.getHours() + 1)).slice(-2) + ':' + ('0' + now.getMinutes()).slice(-2) + ':' + ('0' + now.getSeconds()).slice(-2);
I've tested and while the format works fine, the time is off by an hour. Is it because of the Daylight Savings Time? How do I get the actual local time for the user?
In your code wrote:
...('0' + (now.getHours() + 1)).slice(-2)...
Try to remove this plus one
Additional you can check if Day Savings Time with:
if (now.dst()) { alert ("Daylight savings time!"); }
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
Based at answer similar issue
You should use the toISOString() method to convert the Date object to the ISO-8601 standard format:
now.toISOString();
The ISO-8601 date format puts the time information into a universal form which includes optional timezone information (likely the source of your issues).

Force browser to display all dates to specific timezone [duplicate]

This question already has answers here:
Convert date to another timezone in JavaScript
(34 answers)
How to initialize a JavaScript Date to a particular time zone
(20 answers)
Closed 9 years ago.
How can I force Browser to display all date objects to use Specific Timezone.Like passing Europe/London.Is there any way to do so??
Update
Here I want is that all Jquery Datepicker open date and time as per Specific Timezone instead of Client's Machine.
You can't "set" the timezone offset, it's a read only property that is based on system settings.
You can generate time and date values for any timezone offset by simply adding the client timezone offset, then adding whatever offset you want (note that javascript Date object's timezone offset has an opposite sense to the usual value, so you add both rather than subtracting one and adding the other).
e.g.
// Provide offsetInMintes to add to UTC to get required time,
// e.g. Nepal Standard Time is UTC +05:45 -> +345 minutes
function generateOffsetTime(offsetInMinutes) {
function z(n){return (n<10? '0' : '') + n;}
var d = new Date();
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + offsetInMinutes);
return [z(d.getHours()),z(d.getMinutes()),z(d.getSeconds())].join(':');
}
alert('The time in Nepal is ' + generateOffsetTime(345));
Edit
You could add your own methods to Date.prototype:
Date.prototype.setOffset = function(offsetInMinutes, offsetName) {
this._offsetInMinutes = offsetInMinutes;
this._offsetName = offsetName;
};
Date.prototype.getOffsetFullDate = (function() {
var months = ('January February March April May June July ' +
'August September October November December').split(' ');
var days = 'Sunday Monday Tuesday Wednesday Thursday Friday Saturday'.split(' ');
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return days[d.getDay()] + ' ' + d.getDate() + ' ' + months[d.getMonth()] +
', ' + this.getFullYear();
}
}());
Date.prototype.getOffsetTime = (function() {
function z(n){return (n<10? '0' : '') + n;}
return function() {
var d = new Date(+this);
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + this._offsetInMinutes);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' +
z(d.getSeconds()) + ' ' + this._offsetName;
}
}());
var d = new Date();
d.setOffset(345, 'NST')
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
Note that this keeps the date object's original timevalue, it adjusts values as they are retrieved so the timezone can be changed to get different values for the same date object, so you could continue with:
d.setOffset(600, 'AEST');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
d.setOffset(630, 'LHI');
console.log(d.getOffsetFullDate() + ' ' + d.getOffsetTime());
But I still think it's better to build your own date constructor that leverages the built in Date rather than extends it.
Moment.js is a great library which could help you to achieve this.

Categories