ChatGPT解决这个技术问题 Extra ChatGPT

Moment.js transform to date object

Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.

Example:

var oldDate = new Date(),
    momentObj = moment(oldDate).tz("MST7MDT"),
    newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
What output do you expect and what output do you get?
4 row get me so output: (Date object) Time with offset Thu Aug 01 2013 15:23:49 GMT+0300 (Финляндия (лето)) But timezone must be MST7MDT
Wednesday 24th 2019, 12:47:48 am is this possible to convert into 2019-04-23T19:17:48.000Z ? @vadim.zhiltsov
Date objects don't have a timezone, they are just an offset from 1970-01-01T00:00:00Z. So when you call toDate, the returned object has lost the timezone information you attached to the moment object with .tz("MST7MDT"). That's why libraries like moment.tz exist, to supplement the bare bones capability of the built–in Date object which only understands UTC and the host timezone, that's it.

J
Josh Hunt

Use this to transform a moment object into a date object:

From http://momentjs.com/docs/#/displaying/as-javascript-date/

moment().toDate();

Yields:

Tue Nov 04 2014 14:04:01 GMT-0600 (CST)

@Spencer - Yes, it answers the title, and toDate is indeed how to get a Date object from a moment. But the code in the body of the question asks about time zone conversion - which Date cannot do. Unless Mountain time is indeed the user's time zone, then I'm not sure how this answered the question.
@Matt it just depends on which part of the question you're looking at. A majority of people search google and see that this title lines up with their question and upvote the answer which answers the title, not the body of the question. That might explain why this has the most upvotes even though it doesn't technically help the OP.
Is this actually the correct answer? The question was how to transform the moment object to a javascript date but with TIMEZONE. It still reverts back to the local timezone when change to javascript date object.
Hey guys check this link momentjs.com/guides/#/warnings/js-date. This is discouraged and will be removed in upcoming major release.
@gtzinos what you're linking and referring to is a separate issue and scenario, e.g passing a string into the moment constructor moment("12/12/2011") is where you would get that message. It has nothing to do with going from moment to date obj moment().toDate()
M
Matt Johnson-Pint

As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.

You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().

Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().

Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:

momentObj.format("YYYY-MM-DD HH:mm:ss")

Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.

A couple of other little things:

While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.

Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.


Thanks Matt! Your answer was useful. As you mentioned about using America/Denver instead of MST7MDT, Is there a map available for these mappings? I am using quite a few such timezones like CET, EET, EST5EDT, CST6CDT, PST8PDT.
is it possible to convert eg: "10:20 AM" (Obtained string time from moment().format('hh:mm A')) to Date object ??
@ram - 1) if you have a moment, just use .toDate(). 2) Don't use comments to ask new questions. That's what the big "Ask Question" button is for.
this is what I needed to use the date. I also needed to change the timezone , thanks
M
Mo.

.toDate did not really work for me, So, Here is what i did :

futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))

hope this helps


This answer doesn't answer the question. The code is a long winded way of writing moment().add(1, 'd').toDate().
Y
Yasith Prabuddhaka

Since momentjs has no control over javascript date object I found a work around to this.

const currentTime = new Date(); const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss"); const convertTimeObject = new Date(convertTime);

This will give you a javascript date object with the converted time


The format "YYYY-MM-DD HH:mm:ss" is not supported by Safari, so the result is null. The format should be "YYYY-MM-DDTHH:mm:ss" (use an ECMAScript supported format, a "T" between the date and time parts).
V
Vijay Joshua Nadar

The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,

const moment=require('moment-timezone')//import from moment-timezone

Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,

var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/

Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,

newYork.toDate()//will give you the Greenwich ,UK, time.

newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()

In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.


This is the only corrected answer. A more simple code is moment().tz("Asia/Shanghai").utc(true).toDate(). It will give the date, for example, 2022-03-29T23:09:21.452Z which is a local Shanghai time.
k
kizoso

To convert any date, for example utc:

moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()

This answer is wrong. It applies the timezone offset twice: moment().utc() returns values for UTC, then .format( "YYYY-MM-DD HH:mm:ss" ) returns a string that has been set to UTC without a timezone offset so is parsed as local. It doesn't match a default moment format so is parsed by the built in parser. It doens't match any ECMAScript supported format either, so parsing is implementation dependent. Anyway, it is parsed as local so the timezone offset is applied again when creating the Date's time value.
E
Emerson Bottero
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();

nice and clean!!!!


c
chovy

I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.

I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.

The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();


K
Kamil Kiełczewski

try (without format step)

new Date(moment())

var d = moment.tz("2019-04-15 12:00", "America/New_York"); console.log( new Date(d) ); console.log( new Date(moment()) );


new Date(moment()) is equivalent to new Date(). The timezone is only set for d.
F
Feng Zhang

moment has updated the js lib as of 06/2018.

var newYork    = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london     = newYork.clone().tz("Europe/London");

newYork.format();    // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format();     // 2014-06-01T17:00:00+01:00

if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.


A
Anmol K.

new Date(moment()) - could give error while exporting the data column in excel

use

moment.toDate() - doesn't give error or make exported file corrupt