Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage datetime in angular

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

like image 965
Nicolò Scapin Avatar asked Jan 29 '23 18:01

Nicolò Scapin


2 Answers

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.

like image 72
Daniel Netzer Avatar answered Jan 31 '23 08:01

Daniel Netzer


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

like image 45
Borian Avatar answered Jan 31 '23 09:01

Borian