简体   繁体   English

如何在Angular 2/4中将当前日期转换为时间戳

[英]How to convert current date to timestamp in Angular 2/4

I want to convert current date to timestamp.Suppose todays date is 26/4/2019 , then i am doing like this. 我想将当前日期转换为时间戳。假设今天的日期是26/4/2019,那么我正在这样做。

const current = new Date();
const timestamp = current.getTime();

but this gives me 1556532767266. When i am getting date from this , it shows me 'Mon Apr 26 2019 10:12:47' in UTC and 'Mon Apr 26 2019 15:42:47' in local. 但是这给了我1556532767266。当我从中获取日期时,它在UTC上显示为“ Mon Apr 26 2019 10:12:47”,在本地显示为“ Mon Apr 26 2019 15:42:47”。 but i want in this ' Mon Apr 26 2019 00:00:00 ', which is night 12Am 但我想参加这个' 周一Apr 26 2019 00:00:00 ',即晚上12点

Can anyone please help me how to get like this. 谁能帮我如何获得这样的服务。

You can set Hours/Min/Seconds to 0 and getTime() 您可以将Hours / Min / Seconds设置为0和getTime()

const current = new Date();

current.setHours(0)

current.setMinutes(0)

current.setSeconds(0)

current.setMilliseconds(0)

const timestamp = current.getTime();

To solve your problem, and many others when dealing with date/times, use Moment.js . 要解决您的问题以及其他处理日期/时间的问题,请使用Moment.js

var moment = require("moment");
var current_timestamp = moment().format("ddd MMM D YYYY 00:00:00");

A moment() call initializes to the current time, but Moment objects can also accept JavaScript Date objects: moment()调用会初始化为当前时间,但是Moment对象也可以接受JavaScript Date对象:

var current_timestamp = moment(new Date());

Check out all the formats available for Moment to convert timestamps any way you want. 查看Moment可用的所有格式,以任意方式转换时间戳。 https://momentjs.com/docs/#/displaying/format/ https://momentjs.com/docs/#/displaying/format/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM