如何将短日期转换为这种格式:DDD MMM DD YYYY GMT+0800(X 国家标准时间)?

How to convert short dates to this format: DDD MMM DD YYYY GMT+0800 (X country standard time)?

当我这样做时 new Date() 我得到:

Thu Dec 28 2017 10:17:58 GMT+0800 (台北標準時間)

如果我将 .valueOf() 申请到那个日期,我会得到:

1514427724039

这就是我想要的。

现在,我需要将 .valueOf() 应用到这样的日期:2017/12/28。我尝试使用 Luxon 来转换日期(因为将 .valueOf() 应用于 YYYY/MM/DD 不会产生数字):

DateTime.fromISO(startDate.replace(/\//g, '-')).toRFC2822()
// => Thu, 28 Dec 2017 00:00:00 +0800

但是,应用 valueOf() 会产生 returns 相同的字符串。不是第一个例子中的数字。

我应该怎么做才能从 YYYY/MM/DD 中生成一个数值?刚才我用 DDD MMM DD YYYY GMT+0800 (X country standard time)?

Date 对象将按原样接受 YYYY/MM/DD 字符串。从那里,您可以使用 .getTime() 获取时间戳:

var startDate='2017/12/28'; 
var dateStamp = new Date(startDate); // e.g. "Thu Dec 28 2017 00:00:00 GMT-0600 (Central Standard Time)"
var timeStamp = dateStamp.getTime(); // e.g. 1514440800000

如果您想使用 Luxon,您可以:

var startDate = '2017/12/28';
var DateTime = luxon.DateTime;
// fromISO with regex
console.log( DateTime.fromISO(startDate.replace(/\//g, '-')).valueOf() );
// fromString instead of regex
console.log( DateTime.fromString(startDate, 'yyyy/MM/dd').valueOf() );
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>

如果你想使用momentjs(Luxon的“老大哥”),你可以简单地使用moment(String, String):

var startDate = '2017/12/28';
console.log( moment(startDate, 'YYYY/MM/DD').valueOf() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.js"></script>

默认情况下,luxon 和 moment 都将字符串解析为本地时间。


您也可以使用原版 JavaScript,请参阅 Date:

  • new Date(year, month, day)参数月份从0开始
  • new Date(dateString)(符合 IS0 8601 标准的格式,例如 2017-12-28。在 Firefox <=3 和 IE <=8 上不受支持)

var startDate = '2017/12/28';
var arr = startDate.split('/');
console.log( new Date(arr[0], arr[1]-1, arr[2]).valueOf() );
console.log( new Date(startDate.replace(/\//g, '-')).valueOf() );

请注意:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

我认为您忘记了类型。

fromISO() returns Luxon DateTime 对象,但 toRFC2822 returns 日期的 RFC 2822 字符串表示形式。

所以您的 valueOf() 是在字符串上调用的,而不是 DateTime。

正如其他人所指出的,您只需对 fromISO() 的结果调用 valueOf()

举例说明:

var dt = luxon.DateTime.fromISO('2017-12-05'); // returns a Luxon DateTime object
console.log('fromISO returns an', typeof dt);

var rfc = dt.toRFC2822(); // returns a string
console.log('toRFC2822 returns a', typeof rfc);

var valueOfRFC = rfc.valueOf(); // string.valueOf() is just that string
console.log('strings are their own values?', rfc === valueOfRFC);

var valueOfDT = dt.valueOf(); // this is what you want
console.log('value of datetime', valueOfDT);
<script src="https://moment.github.io/luxon/global/luxon.min.js"></script>