How to change a unix datetime into a different timezone unix datetime - javascript

I get datetime state like: "2022-05-18T18:30:00.000Z" - a moment datetime, then converts it to unix. But I do convert it in my local timezone, How do I change the timezone of the unix datetime and return in same unix format.
Timezone I get - Asia/Singapore
Code:
this.state.startTimeDate.unix() //This is how I convert it to unix format
How to change this unix to a different timezone ?

You could try converting the date to the client timezone before converting back to unix using moment like this ...
moment
.unix(1399335987)
.tz('MST')
.format('YYYY-MM-DDTHH:mm:ssZ');
And you get
"2022-05-20T17:01:27-07:00"
Before converting back to unix again.
Hope this helps

I'm not quite sure how accurate or correct my "solution" is, but having to generate unix timestamps for a Discord bot I ended up doing something similar to this (albeit a bit shorter):
const moment = require('moment-timezone')
const riseTime = moment("05:41", 'HH:mm', 'America/Toronto') // Moment<2022-06-14T05:41:00+00:00>
let bootlegUnix = Math.round(riseTime.valueOf() / 1000) // 1655185260
I'm basically an idiot but this accomplished what I was going for.

Related

Convert date with timezone to UTC?

A quick question. I have a ISO string date:
2022-07-03T10:51:09+02:00
this date as you can see has timezone included (+02:00).
Question: How to convert it into UTC date? Using e.g. date-fns or moment?
Edit: Should I just simply add "02:00" hours to current date? So it would be 12:51:09?
Trivially new Date(isoString).toISOString(), no libraries required.
const input = "2022-07-03T10:51:09+02:00";
console.log(`${input} in UTC:\n${new Date(input).toISOString()}`);
In my view, timezone is simply the representation of the same timestamp across different geographies (no. of seconds elapsed since unix time 0 is the same everywhere). So be careful while adding/removing time manually from the existing timestamp.
You can do that using moment.js like this:
var someday = moment('2022-07-03T10:51:09+02:00');
console.log(someday.utc().format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment-with-locales.min.js"></script>

How to format a string in UTC to the configured timezone on Moment

I have the following string, which is in UTC:
2022-02-01T00:00:00Z
I have already configured my timezone, so I do not want to mess/call .tz()
I know that this string is in UTC, but I am not managing to convert from UTC to the defined timezone, which in this example is pacific/wallis.
I have tried many things, as
const utc = moment.utc('2022-02-01T00:00:00Z').toDate()
const inConfiguredTimeZone = utc.format()
My desire is to get this timestamp 2022-02-01T00:00:00Z and have converted to the defined timezone on Moment
I need to tell moment that "This string is in UTC, please give me the converted timestamp in the defined time zone"
If you just want to format a UTC timestamp in your current timezone (determined by your computer's time settings) just use
let s = moment("2022-02-01T00:00:00Z").format();
This will produce a string like 2022-02-01T12:00:00+12:00 if you are currently in a timezone that has a UTC offset of +12 hours (like pacific/wallis) or 2022-02-01T01:00:00+01:00 if you are currently in a timezone that has a UTC offset of +1 hours (like europe/berlin)
If you want it converted to a specific timezone use
let s = moment("2022-02-01T00:00:00Z").tz("pacific/wallis").format();
This will produce 2022-02-01T12:00:00+12:00, regardless of your current timezone.

How to convert Moment.js moment to unix timestamp

I see a lot in the Moment.js documentation about getting a Moment from a Unix timestamp. However, I am trying to convert a Moment to a Unix timestamp, and I am not sure how to do that. This is how my moment looks:
const myMomentObject = moment(str_time, 'YYYY-MM-DD');
And I need to convert it to a Unix timestamp.
Unix timestamp can be obtaineded with or without the moment library.
//Moment
const myMomentObject = moment('2021-10-16', 'YYYY-MM-DD');
console.log(myMomentObject.unix());
//Vanilla
const d = new Date('2021.10.16');
console.log(d.getTime() / 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Call unix() on moment object. Reference.
moment('2020-12-12').unix()
To create a Unix timestamp (seconds since the Unix Epoch) from a moment, use the following,
console.log(moment('2021-10-16').unix());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Since your date format follows the ISO_8601 format, i.e. YYYY-MM-DD you do not need to provide the input date format to the moment constructor.

How to make Moment.js ignore the user's timezone?

I've got a form where I input an event that starts at a certain time. Let's say 9am.
To assign a date/time object I'm using MomentJs. The issue comes when displaying it in different time-zones.
In London will show up 9am as intended - in Kiev will show 11am.
How can I make MomentJS and the browser ignore which timezone is relevant for the user, and just displaying the time I'm giving?
Here's my code:
<p>
Start time:
{moment(event.startDate).format("HH:mm")}
</p>
Assuming you have stored the date as utc (which in this case you probably should have), you could use the following:
moment.utc(event.startDate).format("HH:mm")
Let me provide an alternative answer in Vanilla JavaScript. If you want to make it timezone 'neutral', you can first convert it to UTC using toISOString().
const current = new Date();
const utcCurrent = current.toISOString();
console.log(utcCurrent);
If you want to convert it to a specific timezone, such as London, you can use toLocaleString(). Do take note of the browser support for the timezone though.
const londonTime = new Date().toLocaleString('en-US', { timeZone: 'Europe/London' })
console.log(londonTime);
What you want is a normalized Datetime. This can get a little confusing since the concept of timezones is a rather arbitrary construct.
I like to think of Datetime values as "absolute" and "relative". An "absolute" Datetime is one that is true regardless of which timezone you're in. The most common example of these are UTC(+000) and UNIX Time (also known as Unix epoch, POSIX Time or Unix Timestampe).
UTC is pretty obvious. Its the current time at +000 timezone. UNIX time is a bit more interesting. It represents the number of seconds that have elapsed since January 1, 1970.
You should always store data, in both client and backend, as an "absolute" time. My preference is UNIX time since its represented as a single integer (nice and clean).
moment.js does this for you. When you instantiate your moment object, you can use:
var date = moment.utc(utcString)
or for Unix Time
var date = moment.unix(unixInt)
You can then use this object to display the date in any form you wish:
console.log(date.tz.("America/Toronto"))
The only way I could solve this is by removing the timezone and milliseconds info from the string. I used date-fns lib but I imagine moment will work the same way.
import { format } from 'date-fns'
const myDateTimeString = '2022-02-22T19:55:00.000+01:00'
const dateTimeWithoutTimezone = myDateTimeString.slice(0, 16) // <- 2022-02-22T19:55
format(new Date(dateTimeWithoutTimezone), 'HH:mm')

Converting a DateTime Object to a specific timezone

I have a dateTime string "2019-02-14 17:18:22".
I would like to convert this above-mentioned dateTime string to a specific timezone dateTime .
Here the timezone will be extracted from another dateTime string - "2019-02-14T17:28:24+08:00".
I did look up at the utcOffset function but I don't know how to use the offset value (330 in mycase).
Expected result: The first String is fairly simple 5:18 PM .
But once getting converted to the specific timezone, it will be 2:48 PM.
Heres how I use timezone offsets.
I get DateTimeIn, which is offset to (UTC+00:00) from the server.
Then to convert to the browser's timezone (UTC-05:00), i use: getTimezoneOffset() to update the object to the local timezone.
var dateObj = new Date(DateTimeIn);
dateObj.setMinutes(dateObj.getMinutes() + dateObj.getTimezoneOffset());
Without this, my server downloaded datetimes are offset and unusable.

Categories

Resources