最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to manage datetime in angular - Stack Overflow

programmeradmin8浏览0评论

I'm working with 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 withconsole.log.

I need the format to be: 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?

I upload my code here

is there a way to manage datetime in angular simply?

thanks

I'm working with 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 withconsole.log.

I need the format to be: 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?

I upload my code here

is there a way to manage datetime in angular simply?

thanks

Share Improve this question asked Jan 30, 2018 at 11:10 Nicolò ScapinNicolò Scapin 2401 gold badge4 silver badges16 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

You can just use the Date object, to get current Date you can use something like

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.

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

after correcting import statement you can subtract time and can format it as console.log(moment().subtract(9,'hours').format('YYYY-MM-DD HH:mm:ss'));

You can do it like this: Consider, you are fetching some kind of date from a json file in the following format "dt":1517216400,

Now in the ts file of the ponent you want to fetch that data and change that into readable date format. 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.

Hope it helps, Cheers

The correct import is

import * as moment from 'moment';
# Or 
import moment from 'moment';
发布评论

评论列表(0)

  1. 暂无评论