简体   繁体   English

如何以角度管理日期时间

[英]How to manage datetime in angular

I'm working with Angular(v5).我正在使用 Angular(v5)。 I have some problem with Datetime.我对日期时间有一些问题。

I need the current time and I have to save it in a variable.我需要当前时间,我必须将它保存在一个变量中。 After that I have to subtract an interval of hours (8 hours or an hour) and save the result in a variable and then do it with console.log .之后,我必须减去一个小时的间隔(8 小时或一小时)并将结果保存在一个变量中,然后使用console.log

I need the format to be: YYYY-MM-DD HH:mm:ss我需要的格式是: YYYY-MM-DD HH:mm:ss

I tried to integrate moment.js without fail but I always get errors in the console, how can I solve?我尝试集成moment.js没有失败,但我总是在控制台中出现错误,我该如何解决?

I upload my code here在这里上传我的代码

is there a way to manage datetime in angular simply?有没有办法简单地以角度管理日期时间?

thanks谢谢

You can just use the Date object, to get current Date you can use something like您可以只使用 Date 对象,要获取当前日期,您可以使用类似

const dateNow = new Date();

to subtract just do something like this减去只是做这样的事情

const dateNowMinusEightHours = new Date(new Date(dateNow).getTime() - 1000 * 60 * 60 * 8)

there's no need to import moment.js for simplistic use and manipulation of Dates.无需为了简单的使用和操作日期而导入 moment.js。

your import statement is incorrect您的导入语句不正确
change statement to:将语句更改为:

import moment from 'moment';

your desired format can be achieved with the following statement:您可以使用以下语句实现所需的格式:

time.format('YYYY-MM-DD HH:mm:ss')

I forked your code and added the formating and your time calculation functions:我分叉了您的代码并添加了格式和时间计算功能:
time format example 时间格式示例

更正导入语句后,您可以减去时间并将其格式化为console.log(moment().subtract(9,'hours').format('YYYY-MM-DD HH:mm:ss'));

The correct import is正确的导入是

import * as moment from 'moment';
# Or 
import moment from 'moment';

You can do it like this: Consider, you are fetching some kind of date from a json file in the following format "dt":1517216400,您可以这样做:考虑一下,您正在从以下格式的 json 文件中获取某种日期“dt”:1517216400,

Now in the ts file of the component you want to fetch that data and change that into readable date format.现在在组件的 ts 文件中,您要获取该数据并将其更改为可读的日期格式。 Then you should follow this approach:那么你应该遵循这个方法:

** **

> let alldates = res['list'].map(res => res.dt)
>     alldates.forEach((res) => {
>         let jsdate = new Date(res * 1000)
>         weatherDates.push(jsdate.toLocaleTimeString('en', { year: 'numeric', month: 'short', day: 'numeric' }))
>     })

** **

Here, I've fetched the date present inside the list.在这里,我获取了列表中的日期。 Then applied the toLocaleTimeString() function to change into the format which I wanted.然后应用 toLocaleTimeString() 函数更改为我想要的格式。

Hope it helps, Cheers希望它有帮助,干杯

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

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