Converting Timestamp String with Timezone into UTC in Javascript Without External Packages - javascript

I have a timestamp string and a timezone, and I need to convert that into a Date object in UTC without using moment-timezone.
Essentially, I wanna be able to do this without external dependencies:
var date = moment.tz("2021-03-03 14:40:40", "Asia/Dhaka")
Is this possible? I'd rather not have to download a rather hefty package just for this.

Check it out
let dateString = new Date("2021-03-03 14:40:40").toDateString('en-US', {timeZone: 'Asia/Dhaka'})
console.log(dateString);

Related

How to obtain a local timezone Date from a date string in javascript?

I am building an online store, most of my customers (basically all) are located in a given timezone, but my infrastructure is located in other timezone (we can assume it's UTC). I have the option for my clients to select a date for their orders, the problem is that my date component represents dates like this "YYYY-MM-DD". In am using the Date constructor like this:
let dateString = "2019-06-03"
let date = new Date(dateString)
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString
The problem with this is that I want the UTC representation to be calculated from the local timezone, not the other way around. Let's suppose in am located in GMT-5, when I say let date = new Date("2019-06-06") I want to see "2019-06-03T00:00:00.000 GMT-5" , and the ISOString should be "2019-06-03T05:00:00.000Z". How can I do this ?
What you are trying to achieve can be done by appending the string T00:00:00 to the dateString before passing it to the Date() constructor.
But a word of caution, manipulating the timezone/offsets manually like this might result in incorrect data being presented.
If you are storing and retrieving all the order timestamps in UTC only, it will avoid timezone related issues and you might not need to process the timestamps like this.
let dateString = "2019-06-03"
let date = new Date(dateString + "T00:00:00")
console.log(date) //This will print the local time zone representation of my dateString
console.log(date.toISOString()) //This will print the utc equivalent of my dateString

Convert time zone of XML parsed time and date with moment.js

I'm parsing a XML file with Javascript and I would like to convert a date to my local time zone using moment.js but I'm stuck. The basic parsing consists of getting the date:
document.write(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue);
Which generates something like 31/12/2016 23:00. With moment.js it's possible to format the date like this:
var utcDate = moment.utc('31/12/2016 23:00', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write(localDate);
Which writes 01/01/2017 01:00 in my current time zone. But I can't figure out how to use the method above with the parsing. Tried modifying the variable but only getting "Invalid date" as a result.
var utcDate = moment.utc('x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue', 'DD/MM/YYYY HH:mm');
var localDate = utcDate.local();
document.write (localDate);
Does anyone have any tips? Might be other solutions than using moment.js but it seemed like the best and most flexible option.
You've put your XML traversal inside a string. That traversal won't happen if it's not actual javascript. Additionally, moment.js will try to parse that literal string as a date, NOT the value from that traversal.
'x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue'
You need to unquote your traversal to get its value, then feed that to moment.js.
var utcDate = moment.utc(x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue, 'DD/MM/YYYY HH:mm');

Is it Possible in javascript to restrict date to specific Timezone [duplicate]

I know I can get the local timezone offset via new Date().getTimeZoneOffset(). But where did Javascript get that information? Is there a way I can set it, so that all future Date objects have the offset I want? I tried searching the DOM in Firebug, but couldn't find anything.
What I am trying to accomplish is converting epoch times to readable format, but it needs to be in US/Central, no matter what the browser's OS setting. Because I am using US/Central, it's not a fixed difference from GMT. So instead of a bunch of super nasty conversion steps, why can't I just tell Javascript that I'm actually in US/Central?
Currently, Moment-Timezone enables us to set the "browser's" default timezone by using moment.tz.setDefault().
You'll have to use moment() instead of Date(), but this is still a nice upgrade over the weird JS Date object.
I know I can get the local timezone offset via new Date().getTimeZoneOffset(). But where did Javascript get that information?
An implementation of ECMAScript is expected to determine the local time zone adjustment.
Is there a way I can set it, so that all future Date objects have the offset I want?
No.
So instead of a bunch of super nasty conversion steps, why can't I just tell Javascript that I'm actually in US/Central?
Have you considered using a library?
I realize this is an old post, but momentJS is a powerful javascript library to manipulate date/time objects
Output format
If you are concerned about the output format, you always need to format you Date object prior to outputting it if you need it in a local timezone (e.g. using Intl) or you a library like dayjs or moment.
Create a new Date object from a date with a non-UTC timezone
You can set an offset in pure JS: new Date('2022-10-29T12:50:00.000+02:00') will contain 2022-10-29T10:50:00.000Z. You just have to always specify the timezone offset in /^[+-][0-2]\d:[0-5]\d$/ format.
console.log(new Date('2022-10-29T12:50:00.000+02:00').toISOString())
// Output
// 2022-10-29T10:50:00.000Z
Get timezone offset string from timezone offset number
Now, if you want to get an offset in that format from (new Date()).getTimezoneOffset() (e.g. -120), you need to
const tzOffsetNumber = (new Date()).getTimezoneOffset()
const tzOffsetString = `${tzOffsetNumber > 0 ? '+' : '-'}${Math.floor(Math.abs(tzOffsetNumber) / 60).toString().padStart(2, '0')}:${(Math.abs(tzOffsetNumber) % 60).toString().padStart(2, '0')}`
Get timezone offset string from IANA timezone
// Note: We need to specify a date in order to also consider DST settings.
const date = new Date()
const ianaTimezone = 'Europe/Bratislava'
const tzOffsetString = new Intl.DateTimeFormat('en', {timeZone: ianaTimezone, timeZoneName: 'longOffset'}).format(date).match(/[\d+:-]+$/)?.[0]

JavaScript: how to convert this utc date time string to local time

I have a UTC date string like this "2013-08-22T00:35:00", how do I use Javascript to convert it to a local computer time? so after conversion the time should be 2013-08-21 20:35
Thanks
Does
new Date("2013-08-22T00:35:00")
work for you?
MDN
Or just use libraries designed for that, like moments.js
moment("2013-08-22T00:35:00");
JavaScript convert datetime string to local on creating new instance.
var date = new Date("2013-08-22T00:35:00");
date.toString() //local date
Here is demo

How to convert a GMT timestamp to Unix timestamp (javascript)

I'm parsing an rss feed and each entry has a timestamp such as this: 2009-09-21T21:24:43+04:00
Is there any way to convert this date format to a unix timestamp with javascript?
I just want to be able to record the latest rss entry date, but I need to standardize the time to GMT time or Unix timestamp to do this.
The format appears to be ISO-8601. Assuming that is true, this blog provides a javascript solution to this.
As I met the same problem, the solution involving Google Closure Library would be:
var pattern = "yyyy-MM-ddTHH:mm:ssZZZZZ";
parser = goog.i18n.DateTimeParse(pattern);
var d = new Date();
parser.parse("2009-09-21T21:24:43+04:00", d);
unixTime = d.getTime();

Categories