javascript Moment.js 转换为日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17987647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Moment.js transform to date object
提问by vadim.zhiltsov
Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
使用 Moment.js 我无法将正确的时刻对象转换为带时区的日期对象。我无法得到正确的日期。
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())
回答by Chandrew
Use this to transform a moment object into a date object:
使用它来将一个时刻对象转换为一个日期对象:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
来自http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
产量:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
回答by Matt Johnson-Pint
As long as you have initialized moment-timezonewith the data for the zones you want, your code works as expected.
只要您使用所需区域的数据初始化moment-timezone,您的代码就会按预期工作。
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format()
.
您正确地将时刻转换为时区,这反映在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()
.
切换到 UTC 不仅会删除偏移量,还会更改回 UTC 时区。如果您打算这样做,则根本不需要原始.tz()
调用。你可以这样做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:
也许您只是想更改输出格式字符串?如果是这样,只需为format
方法指定您想要的参数:
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.
关于代码的最后几行 - 当您Date
使用返回对象时toDate()
,您放弃了 moment.js 的行为并返回到 JavaScript 的行为。JavaScriptDate
对象将始终以运行它的计算机的本地时区打印。对此,moment.js 无能为力。
A couple of other little things:
一些其他的小事情:
While the moment constructor cantake a
Date
, it is usually best to not use one. For "now", don't usemoment(new Date())
. Instead, just usemoment()
. 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 aDate
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 asAmerica/Denver
.
虽然构造函数可以采用
Date
,但通常最好不要使用。对于“现在”,不要使用moment(new Date())
. 相反,只需使用moment()
. 两者都可以工作,但这是不必要的冗余。如果您正在解析一个字符串,请将该字符串直接传递给 moment。不要尝试首先解析它Date
。您会发现 moment 的解析器更加可靠。MST7MDT
出于向后兼容性的原因,时区之类的存在。它们源自 POSIX 风格的时区,其中只有少数在 TZDB 数据中。除非绝对必要,否则您应该使用诸如America/Denver
.
回答by Mawaheb
.toDate
did not really work for me, So, Here is what i did :
.toDate
并没有真正对我来说有效,所以,这是我所做的:
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
希望这可以帮助
回答by Yasith Prabuddhaka
Since momentjs has no control over javascript date object I found a work around to this.
由于 momentjs 无法控制 javascript 日期对象,因此我找到了解决方法。
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
这将为您提供一个带有转换时间的 javascript 日期对象
回答by Emerson Bottero
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
漂亮干净!!!!
回答by 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.
我需要在我的日期字符串中包含时区信息。我最初是在使用,moment.tz(dateStr, 'America/New_York').toString();
但后来我开始收到关于将该字符串送回 moment 的错误。
I tried the moment.tz(dateStr, 'America/New_York').toDate();
but then I lost timezone information which I needed.
我尝试了moment.tz(dateStr, 'America/New_York').toDate();
但后来我丢失了我需要的时区信息。
The only solution that returned a usable date string with timezonethat could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
返回带有时区的可用日期字符串可以反馈到时刻的唯一解决方案是moment.tz(dateStr, 'America/New_York').format();
回答by kizoso
To convert any date, for example utc:
要转换任何日期,例如 utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
回答by 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-timezoneinstead of the default moment(ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
这个问题有点晦涩。我会尽力解释这一点。首先,您应该了解如何使用moment-timezone。根据这里的答案 TypeError: moment().tz is not a function,您必须从moment-timezone导入 moment而不是默认 moment(当然,您必须先 npm install moment-timezone !)。为清楚起见,
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,
现在为了使用时区功能,请使用moment.tz("date_string/moment()","time_zone")(访问https://momentjs.com/timezone/了解更多详情)。此函数将返回具有特定时区的时刻对象。为清楚起见,
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,
现在,当您尝试使用 moment 的toDate()(ISO 8601 格式转换)转换 newYork(moment 对象)时,您将获得英国格林威治的时间。有关更多详细信息,请阅读有关 UTC 的这篇文章https://www.nhc.noaa.gov/aboututc.shtml。但是,如果您只想要这种格式的本地时间(纽约时间,根据此示例),只需将方法.utc(true)和arg true 添加到您的时刻对象。为清楚起见,
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.tzconsiders 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.
简而言之,moment.tz 会考虑您指定的时区,并将您的当地时间与格林威治时间进行比较,以得出结果。我希望这是有用的。
回答by Feng Zhang
moment has updated the js lib as of 06/2018.
截至 2018 年 6 月,Moment 已更新了 js 库。
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.
如果您可以自由使用 Angular5+,那么在这里使用 datePipe 功能比使用时区功能更好。我必须使用 moment.js,因为我的项目仅限于 Angular2。
回答by Kamil Kie?czewski
try (without format
step)
尝试(无需format
步骤)
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()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>