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.
Related
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>
Hello I have a function which converts a local time to UTC using the local timezone and date:
this.conversion.dateTimeToTime('2022-07-04 12:30', 'America/Los_Angeles');
public dateTimeToTime(date, timezone = 'UTC') {
date = new Date(date);
return date.toLocaleTimeString('en-GB', {timeZone: timezone, hour12: false});
}
}
this is 12:30 local to UTC which should be 20:30(ish) but the output is 4:30utc instead going backwards
I am wondering what I am doing wrong
Thanks
Keeping date as simple date string(2022-01-31) causes data loss in JS and providing it to Date constructor can result in wrong date. Check this SO question for more.
Generally I convert my date to ISO format by using Date.toISOString. Next when I want to parse it as JS Date object, I use parseISO method of date-fns.
Here is a CodeSandbox example: https://codesandbox.io/s/summer-bush-iv0h2g?file=/src/index.js
I have used moment-tz instead:
import * as moment from "moment-timezone";
let blah = moment.tz("2019-06-03 12:30", "America/Los_Angeles");
console.log(blah.format());
console.log(blah.clone().tz("UTC").format());
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.
I have a UTC time with offset like below. I'm trying to format the UTC date time string using format function from date-fns library.
import { format } from "date-fns";
const utcDateTime = "2021-10-14T21:03:56.3256046+00:00";
const formattedDate = format(new Date(utcDateTime), "MM/dd/yyyy hh:mm");
What I'm expecting is 10/14/2021 21:03, a 24 hour time format but what I get is 10/14/2021 04:03, a converted date time for my timezone.
How to display the date and time exactly like with UTC time instead of converting the date time to local timezone?
I created a working example using CodeSandbox. Could anyone please help?
After spending a lot of time, I was able to achieve the desired result using the plain JavaScript Date object and its functions.
First, parsing the date time string and converting it to ISO string using toISOString() function.
Second, splitting the formatted date and time extracts from the ISO string.
Below is the code
const formatToUTCDateTime = (dateString) => {
const date = new Date(Date.parse(dateString));
const formattedDate = date.toISOString().split("T")[0].split("-");
const formattedTime = date.toISOString().split("T")[1].split(":");
return `${formattedDate[1]}/${formattedDate[2]}/${formattedDate[0]} ${formattedTime[0]}:${formattedTime[1]}`;
};
console.log("Result - ", formatToUTCDateTime("2021-10-14T20:03:56.3256046+00:00"));
I have a date with time and a timezone.
I need this formatted a specific way, which is why I am using moment.
Say the date string I want to put in is 2018-12-31 02:00:00.000 +00:00
I convert it into a specific format doing the following:
const properDate = moment(date, 'YYYY-MM-DD hh:mm:ss:ms')
However this is assuming the date is in UTC, and I want it to be in America/New York timezone, so the date and time I am expecting is actually:
2018-12-30 21:00:00.000
So my question is, how do I add in the timezone to moment when converting a date/time to a specific format?
I know it isn't as simple as passing a parameter. Is it another function I should call?
I have tried
const properDate = moment(date, 'YYYY-MM-DD hh:mm:ss:ms').tz('America/New_York')
but that didn't work either.
Edit: I should also mention that I am also using moment-timezone. It just seems that I can't get it to format the way I need it to as well as get it in the proper timezone.
So basically, I would think I could do something like:
const momentDate = moment(date)
const properDate = momentDate.tz(timezone).format('YYYY-MM-DD hh:mm:ss:ms')
Unfortunately as long as I try to format it, it won't work either.
Use moment.tz for parsing time string using a given timezone (e.g. 'America/New_York') while tz() is for converting between zones.
Here a live sample:
const date = '2018-12-30 21:00:00.000';
const properDate = moment.tz(date, 'YYYY-MM-DD hh:mm:ss.SSS', 'America/New_York')
console.log(properDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>