How to format a UTC date as a `YYYY-MM-DD hh:mm:ss` string using NodeJS?
Asked Answered
R

27

355

Using NodeJS, I want to format a Date into the following string format:

var ts_hms = new Date(UTC);
ts_hms.format("%Y-%m-%d %H:%M:%S");

How do I do that?

Rupertruperta answered 18/5, 2012 at 2:27 Comment(10)
It's kind of a bother to do without any libraries. I recommend using datejsProgeny
or momentjsInfix
or TempusAsp
Tempus worked great. Ad issues will moment.Rupertruperta
These comments should be answers! Perhaps you could move them to answers so that Tampa can accept one of them?Lepsy
Neither Datejs nor Tempus are Node libraries (though they can be used with Node you can't use the npm library installer). As no one has put these up as actual answers, I've done it myself.Lepsy
@Tampa: does one of the answers fit your needs? If so, can you mark one of them as the answer so that we don't get lots of open questions left on Stack? Cheers.Lepsy
why not just simple new Date().toUTCString()? `Une
@JulianKnight—no, they should not be. An answer should not be dependent on a library that isn't asked for. There are many, many date formatting libraries, should there be one answer for each?Perfectly
@Perfectly - Actually, he didn't say in the Q that he didn't want a library, only that he needed an answer, my comment (from 4 years ago!) was to encourage people to actually give an answer rather than a comment. You can see from my answer that I know full well there are many and I waited a week to see if anyone else would give any kind of answer. Such criticism after more than 4 years isn't perhaps that useful?Lepsy
H
725

If you're using Node.js, you're sure to have EcmaScript 5, and so Date has a toISOString method. You're asking for a slight modification of ISO8601:

new Date().toISOString()
> '2012-11-04T14:51:06.157Z'

So just cut a few things out, and you're set:

new Date().toISOString().
  replace(/T/, ' ').      // replace T with a space
  replace(/\..+/, '')     // delete the dot and everything after
> '2012-11-04 14:55:45'

Or, in one line: new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')

ISO8601 is necessarily UTC (also indicated by the trailing Z on the first result), so you get UTC by default (always a good thing).

Hawn answered 4/11, 2012 at 14:57 Comment(9)
In case you get error, Object has no method 'toISOString', you missed newAnguiano
One thing to note is that using regular expressions this way is slow and you don't even need them here, this: new Date().toISOString().replace('T', ' ').substr(0, 19) works just fine.Tango
Note that by removing the time zone, it now represents a different moment in time in every time zone with a different offset.Perfectly
@Perfectly You can say that about any date time representation which doesn't have an explicit timezone.Stefaniestefano
@Hawn how can I cut off the seconds?Deliladelilah
Improvement on the answer: (new Date()).toISOString().slice(0,16).replace('T',' ') which removes the regex. This gives the answer without seconds.Lepsy
You can use simple toLocaleStringMethod provided on Date object new Date().toLocaleString('default', { dateStyle: 'medium', timeStyle: 'short' })Brewer
If you want just yyyy-mm-dd you can do new (Date()).toISOString().split('T').pop();Brainwash
@Tango As your post 8 years back, some code becomes depreciated. So little modification of your contribution new Date().toISOString().replace("T", " ").substring(0, 19)Sherise
L
134

UPDATE 2021-10-06: Added Day.js and remove spurious edit by @ashleedawg
UPDATE 2021-04-07: Luxon added by @Tampa.
UPDATE 2021-02-28: It should now be noted that Moment.js is no longer being actively developed. It won't disappear in a hurry because it is embedded in so many other things. The website has some recommendations for alternatives and an explanation of why.
UPDATE 2017-03-29: Added date-fns, some notes on Moment and Datejs
UPDATE 2016-09-14: Added SugarJS which seems to have some excellent date/time functions.


OK, since no one has actually provided an actual answer, here is mine.

A library is certainly the best bet for handling dates and times in a standard way. There are lots of edge cases in date/time calculations so it is useful to be able to hand-off the development to a library.

Here is a list of the main Node compatible time formatting libraries:

  • Day.js [added 2021-10-06] "Fast 2kB alternative to Moment.js with the same modern API"
  • Luxon [added 2017-03-29, thanks to Tampa] "A powerful, modern, and friendly wrapper for JavaScript dates and times." - MomentJS rebuilt from the ground up with immutable types, chaining and much more.
  • Moment.js [thanks to Mustafa] "A lightweight (4.3k) javascript date library for parsing, manipulating, and formatting dates" - Includes internationalization, calculations and relative date formats - Update 2017-03-29: Not quite so light-weight any more but still the most comprehensive solution, especially if you need timezone support. - Update 2021-02-28: No longer in active development.
  • date-fns [added 2017-03-29, thanks to Fractalf] Small, fast, works with standard JS date objects. Great alternative to Moment if you don't need timezone support.
  • SugarJS - A general helper library adding much needed features to JavaScripts built-in object types. Includes some excellent looking date/time capabilities.
  • strftime - Just what it says, nice and simple
  • dateutil - This is the one I used to use before MomentJS
  • node-formatdate
  • TimeTraveller - "Time Traveller provides a set of utility methods to deal with dates. From adding and subtracting, to formatting. Time Traveller only extends date objects that it creates, without polluting the global namespace."
  • Tempus [thanks to Dan D] - UPDATE: this can also be used with Node and deployed with npm, see the docs

There are also non-Node libraries:

  • Datejs [thanks to Peter Olson] - not packaged in npm or GitHub so not quite so easy to use with Node - not really recommended as not updated since 2007!
Lepsy answered 23/5, 2012 at 9:25 Comment(5)
This is also highly relevant date-fns.org (github.com/date-fns/date-fns)Abidjan
The folk(s) behind Moment have an experiment called Luxon as of Feb 2018 moment.github.io/luxon/index.htmlStroboscope
Thanks @alxndr, looks like a useful reboot.Lepsy
Moment + toISOString() on RunKit: runkit.com/shanekenyon87/5b845b0a64ab3f0012c9c607Cervin
Thanks a lot. I used dayjs to format a Unix Timestamp into a human-readable form, super easy: const dayjs = require('dayjs') dayjs(1318781876406).format("HH:mm DD-MM-YYYY") Intraatomic
B
84

There's a library for conversion:

npm install dateformat

Then write your requirement:

var dateFormat = require('dateformat');

Then bind the value:

var day=dateFormat(new Date(), "yyyy-mm-dd h:MM:ss");

see dateformat

Bamford answered 29/8, 2013 at 10:50 Comment(5)
it doesn't support CJS modules though, can't get it to work in NextJSCellulose
internal/modules/cjs/loader.js:1167 throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath); ^ Error [ERR_REQUIRE_ESM]: Must use import to load ES Module:Glorygloryofthesnow
@EmmanuelMericdeBellefon it's asked for Node.js, why it does have to work NextJS?Bamford
NextJS has a node runtime for the backend. AFAIU this library exposes only ESM modules which we can't import when we use CJS in a project.Cellulose
@EmmanuelMericdeBellefon, still, the question is related to NodeJs, not NextJs.Fula
E
52

I have nothing against libraries in general. In this case a general purpose library seems overkill, unless other parts of the application process dates heavily.

Writing small utility functions such as this is also a useful exercise for both beginning and accomplished programmers alike and can be a learning experience for the novices amongst us.

function dateFormat (date, fstr, utc) {
  utc = utc ? 'getUTC' : 'get';
  return fstr.replace (/%[YmdHMS]/g, function (m) {
    switch (m) {
    case '%Y': return date[utc + 'FullYear'] (); // no leading zeros required
    case '%m': m = 1 + date[utc + 'Month'] (); break;
    case '%d': m = date[utc + 'Date'] (); break;
    case '%H': m = date[utc + 'Hours'] (); break;
    case '%M': m = date[utc + 'Minutes'] (); break;
    case '%S': m = date[utc + 'Seconds'] (); break;
    default: return m.slice (1); // unknown code, remove %
    }
    // add leading zero if required
    return ('0' + m).slice (-2);
  });
}

/* dateFormat (new Date (), "%Y-%m-%d %H:%M:%S", true) returns 
   "2012-05-18 05:37:21"  */
Emrich answered 18/5, 2012 at 5:41 Comment(4)
Whilst this may indeed be useful for learning, I would have to disagree that this is a better result than using a small, well constructed library. A library would be maintained and be more likely to cover edge-cases in design that might not be obvious to you at first sight but could easily bite at some point - date/time calculations are particularly prone to these problems due to their inherent complexity.Lepsy
This is very good usage of the String.replace() method, +1 for creativityWorkbook
No. Absolutely do use a library in this case. The format may change. Even if it does not change, this is adding complexity to the code. Other people maintaining your code would have to spend time, trying to understand this function and making sure that it is correct. Exercises are for school; the question was about real-life usage. Unless, of course, this is your first or second "real" project; then it may be good to do something like that, so you can learn why you shouldn't do it in the future.Inequity
I appreciate the general sentiment of using libraries as proven/battle-hardened code but they can also add deployment complexity. This code delegates all of the calendar-related subtleties to the underlying Date object and just calls e.g., the getUTCDate() method in the appropriate place. Additionally, if anyone finds a bug in this code they can report it here on stackoverflow.com, essentially matching the many-eyes/shallow-bugs aspect of any other library. +1Disparate
A
30

Check the code below and the link to Date Object, Intl.DateTimeFormat

// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")

// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))

// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())

// log format
const parts = new Date().toString().split(' ')
console.log([parts[1], parts[2], parts[4]].join(' '))

// intl
console.log(new Intl.DateTimeFormat('en-US', {dateStyle: 'long', timeStyle: 'long'}).format(new Date()))
Antigorite answered 26/6, 2020 at 19:37 Comment(1)
UPDATE: Added log formatAntigorite
T
17

Easily readable and customisable way to get a timestamp in your desired format, without use of any library:

function timestamp(){
  function pad(n) {return n<10 ? "0"+n : n}
  d=new Date()
  dash="-"
  colon=":"
  return d.getFullYear()+dash+
  pad(d.getMonth()+1)+dash+
  pad(d.getDate())+" "+
  pad(d.getHours())+colon+
  pad(d.getMinutes())+colon+
  pad(d.getSeconds())
}

(If you require time in UTC format, then just change the function calls. For example "getMonth" becomes "getUTCMonth")

Tender answered 14/3, 2016 at 22:27 Comment(1)
If you use this to generate a different output shape, then change the pad function to the following to ensure that it does string concatenation instead of integer math: function pad(n) {return n<10 ? "0"+n : ""+n}Goodly
S
13

The javascript library sugar.js (http://sugarjs.com/) has functions to format dates

Example:

Date.create().format('{dd}/{MM}/{yyyy} {hh}:{mm}:{ss}.{fff}')
Sixth answered 12/4, 2013 at 17:18 Comment(2)
Looks like a really awesome library. Their formatting is pretty slick, and their docs show elegant solutions to a hundred other things I've been frustrated with in JavaScript. Going to give this a try.Extravasation
Just tested this out this morning. Looks really nice and having fun with it.Tula
M
9

I am using dateformat at Nodejs and angularjs, so good

install

$ npm install dateformat
$ dateformat --help

demo

var dateFormat = require('dateformat');
var now = new Date();

// Basic usage
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
dateFormat(now, "isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
dateFormat(now, "hammerTime");
// 17:46! Can't touch this!

// You can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007
...
Mauldin answered 11/7, 2018 at 0:52 Comment(0)
D
8

Use the method provided in the Date object as follows:

var ts_hms = new Date();

console.log(
    ts_hms.getFullYear() + '-' + 
    ("0" + (ts_hms.getMonth() + 1)).slice(-2) + '-' + 
    ("0" + (ts_hms.getDate())).slice(-2) + ' ' +
    ("0" + ts_hms.getHours()).slice(-2) + ':' +
    ("0" + ts_hms.getMinutes()).slice(-2) + ':' +
    ("0" + ts_hms.getSeconds()).slice(-2));

It looks really dirty, but it should work fine with JavaScript core methods

Dairymaid answered 27/2, 2013 at 3:41 Comment(1)
I agree that you need to add 1 to getMonth() since January comes back as 0, but I don't think you want to add 1 to getDate().Tented
C
7

For date formatting the most easy way is using moment lib. https://momentjs.com/

const moment = require('moment')
const current = moment().utc().format('Y-M-D H:M:S')
Congeal answered 20/3, 2020 at 7:18 Comment(2)
Thanks, @Jazeb_007 it's working for me even I don't need toISOString() and toUTCString()Presignify
moment.js will only be in maintenance mode from now on momentjs.com/docs/#/-project-status Please use DateManmade
C
6

Alternative #6233....

Add the UTC offset to the local time then convert it to the desired format with the toLocaleDateString() method of the Date object:

// Using the current date/time
let now_local = new Date();
let now_utc = new Date();

// Adding the UTC offset to create the UTC date/time
now_utc.setMinutes(now_utc.getMinutes() + now_utc.getTimezoneOffset())

// Specify the format you want
let date_format = {};
date_format.year = 'numeric';
date_format.month = 'numeric';
date_format.day = '2-digit';
date_format.hour = 'numeric';
date_format.minute = 'numeric';
date_format.second = 'numeric';

// Printing the date/time in UTC then local format
console.log('Date in UTC: ', now_utc.toLocaleDateString('us-EN', date_format));
console.log('Date in LOC: ', now_local.toLocaleDateString('us-EN', date_format));

I'm creating a date object defaulting to the local time. I'm adding the UTC off-set to it. I'm creating a date-formatting object. I'm displaying the UTC date/time in the desired format:

enter image description here

Colcannon answered 29/4, 2019 at 13:12 Comment(0)
D
4
new Date(2015,1,3,15,30).toLocaleString()

//=> 2015-02-03 15:30:00
Diaconate answered 10/10, 2016 at 13:32 Comment(2)
Welcome to StackOverflow. Please edit your answer, or you could be down-voted. As it is now, it's just a suggestion with no context. Please see here for How to Write a Good Answer.Wigan
This happens with de-locale (hence the toLocaleString): 3.2.2015, 15:30:00Hyalite
O
3

In reflect your time zone, you can use this

var datetime = new Date();
var dateString = new Date(
  datetime.getTime() - datetime.getTimezoneOffset() * 60000
);
var curr_time = dateString.toISOString().replace("T", " ").substr(0, 19);
console.log(curr_time);
Ophelia answered 31/5, 2021 at 1:35 Comment(0)
P
3

Here's a handy vanilla one-liner (adapted from this):

var timestamp = 
  new Date((dt = new Date()).getTime() - dt.getTimezoneOffset() * 60000)
  .toISOString()
  .replace(/(.*)T(.*)\..*/,'$1 $2')
console.log(timestamp)

Output: 2022-02-11 11:57:39

Prudish answered 11/2, 2022 at 20:4 Comment(1)
For me, this was the best way. Thanks.Interracial
L
1

Use x-date module which is one of sub-modules of x-class library ;

require('x-date') ; 
  //---
 new Date().format('yyyy-mm-dd HH:MM:ss')
  //'2016-07-17 18:12:37'
 new Date().format('ddd , yyyy-mm-dd HH:MM:ss')
  // 'Sun , 2016-07-17 18:12:51'
 new Date().format('dddd , yyyy-mm-dd HH:MM:ss')
 //'Sunday , 2016-07-17 18:12:58'
 new Date().format('dddd ddSS of mmm , yy')
  // 'Sunday 17thth +0300f Jul , 16'
 new Date().format('dddd ddS  mmm , yy')
 //'Sunday 17th  Jul , 16'
Lylelyles answered 17/7, 2016 at 15:17 Comment(0)
R
0

I needed a simple formatting library without the bells and whistles of locale and language support. So I modified

http://www.mattkruse.com/javascript/date/date.js

and used it. See https://github.com/adgang/atom-time/blob/master/lib/dateformat.js

The documentation is pretty clear.

Robespierre answered 17/5, 2015 at 21:25 Comment(0)
S
0
new Date().toString("yyyyMMddHHmmss").
      replace(/T/, ' ').  
      replace(/\..+/, '') 

with .toString(), This becomes in format

replace(/T/, ' '). //replace T to ' ' 2017-01-15T...

replace(/..+/, '') //for ...13:50:16.1271

example, see var date and hour:

var date="2017-01-15T13:50:16.1271".toString("yyyyMMddHHmmss").
                    replace(/T/, ' ').      
                    replace(/\..+/, '');
    
                    var auxCopia=date.split(" ");
                    date=auxCopia[0];
                    var hour=auxCopia[1];

console.log(date);
console.log(hour);
Sequin answered 16/1, 2017 at 0:5 Comment(4)
Can you provide some explanation as context behind your answer?Inapprehensible
Welcome to StackOverflow. Please edit your answer, or you could be down-voted. As it is now, it's just a suggestion with no context. Please see here for How to Write a Good Answer.Wigan
@Sequin - now up-voted, for adding context/explanation into your answer. Disclaimer: I wasn't the one who had previously down-voted, as it stands now it looks much better.Inapprehensible
Why the .toString("yyyyMMddHHmmss")?Scrabble
R
0

Here's a lightweight library simple-date-format I've written, works both on node.js and in the browser

Install

  • Install with NPM
npm install @riversun/simple-date-format

or

  • Load directly(for browser),
<script src="https://cdn.jsdelivr.net/npm/@riversun/simple-date-format/lib/simple-date-format.js"></script>

Load Library

  • ES6
import SimpleDateFormat from "@riversun/simple-date-format";
  • CommonJS (node.js)
const SimpleDateFormat = require('@riversun/simple-date-format');

Usage1

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat();
console.log(sdf.formatWith("yyyy-MM-dd'T'HH:mm:ssXXX", date));//to be "2018-07-17T12:08:56+09:00"

Run on Pen

Usage2

const date = new Date('2018/07/17 12:08:56');
const sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
console.log(sdf.format(date));//to be "2018-07-17T12:08:56+09:00"

Patterns for formatting

https://github.com/riversun/simple-date-format#pattern-of-the-date

Royston answered 15/7, 2020 at 7:35 Comment(0)
E
0

import dateFormat from 'dateformat'; var ano = new Date()

<footer>
    <span>{props.data.footer_desc} <a href={props.data.footer_link}>{props.data.footer_text_link}</a> {" "}
    ({day = dateFormat(props.data.updatedAt, "yyyy")})
            </span>
</footer>

rodape

Ebenezer answered 3/1, 2022 at 16:47 Comment(1)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Eventual
O
0

Modern web browsers (and Node.js) expose internationalization and time zone support via the Intl object which offers a Intl.DateTimeFormat.prototype.formatToParts() method.

You can do below with no added library:

function format(dateObject){

    let dtf = new Intl.DateTimeFormat("en-US", {
    year: 'numeric',
    month: 'numeric',
    day: 'numeric',
    hour: 'numeric',
    minute: 'numeric',
    second: 'numeric'
  });
  
  var parts = dtf.formatToParts(dateObject);
  var fmtArr = ["year","month","day","hour","minute","second"];
  var str = "";
  for (var i = 0; i < fmtArr.length; i++) {
    if(i===1 || i===2){
      str += "-";
    }
    if(i===3){
       str += " ";
    }
    if(i>=4){
      str += ":";
    }
    for (var ii = 0; ii < parts.length; ii++) {
    let type = parts[ii]["type"]
    let value = parts[ii]["value"]
      if(fmtArr[i]===type){
        str = str += value;
      }
    }
  }
  return str;
}
console.log(format(Date.now()));
Oleaginous answered 24/11, 2022 at 4:41 Comment(0)
C
0

You can use Light-Weight library Moment js

npm install moment

Call the library

var moments = require("moment");

Now convert into your required format

moment().format('MMMM Do YYYY, h:mm:ss a');

And for more format and details, you can follow the official docs Moment js

Connivent answered 14/12, 2022 at 11:10 Comment(0)
S
0
new Date().toLocaleString("sv") // "2023-04-16 14:31:08"

I.e. Sweden happen to use to the format you are looking for.

Synclastic answered 9/8, 2023 at 12:19 Comment(0)
R
0

An example of code from moment js moment(currentTime, "YYYY-MM-DDTH:mm:ssZ");

  • "T": A literal 'T' character, used to separate the date and time components.
  • "Z": Represents the time zone offset in ISO 8601 format

The result of using this format: 2024-01-20T12:44:00Z

When currentTime is in UTC for client-side, I added it like this and it worked fine, and instead of using moment, you may use dayJS.

Radiotelegram answered 17/1 at 7:9 Comment(0)
T
0

I will utilize the padStart() which is a method of String data type. This method appends a specified string until the resulting string reaches a given length, which is set to 2 in our case.

Both of these methods do not rely on external libraries, keeping your codebase lightweight.

1st example:

  • (Advantage) - The code is more explicit in terms of what it's doing, making it easier to understand for someone reading the code.
  • (Disadvantage) - The code is more verbose and involves multiple lines to format the date and time, which may be considered less concise.

function formatDate(date) {
  const year = date.getUTCFullYear();
  const month = String(date.getUTCMonth() + 1).padStart(2, '0'); // Months are 0-based
  const day = String(date.getUTCDate()).padStart(2, '0');
  const hours = String(date.getUTCHours()).padStart(2, '0');
  const minutes = String(date.getUTCMinutes()).padStart(2, '0');
  const seconds = String(date.getUTCSeconds()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

const ts_hms = new Date(); // You can pass the UTC time here
console.log(formatDate(ts_hms));

2nd example:

  • (Advantage) - This method is more concise and achieves the desired format in a single line of code. It relies on a built-in JavaScript function (toISOString()) and is considered a standardized approach. It requires less code to maintain.
  • (Disadvantage) - Customization may require additional string manipulation.

// another way to do it using `toISOString()`
function formatDateV2(date) {
  return date.toISOString().slice(0, 19).replace('T', ' ');
}

const ts_hms_v2 = new Date(); // You can pass the UTC time here
console.log(formatDateV2(ts_hms_v2));
  • .slice(0, 19): The slice() method is used to extract a portion of the string. In this case, it starts at the beginning (index 0) and takes the first 19 characters. This operation effectively removes the milliseconds and time zone offset from the ISO string, leaving only the date and time components.

  • .replace('T', ' '): The replace() method is used to replace one substring ('T') with another (' '). In ISO 8601 format, the 'T' character separates the date and time components. This step replaces 'T' with a space (' '), making the final output more human-readable.

Theravada answered 21/1 at 19:0 Comment(0)
U
-1

I think this actually answers your question.

It is so annoying working with date/time in javascript. After a few gray hairs I figured out that is was actually pretty simple.

var date = new Date();
var year = date.getUTCFullYear();
var month = date.getUTCMonth();
var day = date.getUTCDate();
var hours = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();

var ampm = hours >= 12 ? 'pm' : 'am';
hours = ((hours + 11) % 12 + 1);//for 12 hour format

var str = month + "/" + day + "/" + year + " " + hours + ":" + min + ":" + sec + " " + ampm;
var now_utc =  Date.UTC(str);

Here is a fiddle

Unavoidable answered 7/5, 2018 at 21:7 Comment(1)
You need to add 1 to the month which is zero-based.Deprivation
M
-1
appHelper.validateDates = function (start, end) {
    var returnval = false;

    var fd = new Date(start);
    var fdms = fd.getTime();
    var ed = new Date(end);
    var edms = ed.getTime();
    var cd = new Date();
    var cdms = cd.getTime();

    if (fdms >= edms) {
        returnval = false;
        console.log("step 1");
    }
    else if (cdms >= edms) {
        returnval = false;
        console.log("step 2");
    }
    else {
        returnval = true;
        console.log("step 3");
    }
    console.log("vall", returnval)
    return returnval;
}
Museum answered 23/8, 2018 at 5:28 Comment(1)
not sure how this answers the question?Mallarme
C
-1

it's possible to solve this problem easily with 'Date'.

function getDateAndTime(time: Date) {
  const date = time.toLocaleDateString('pt-BR', {
    timeZone: 'America/Sao_Paulo',
  });
  const hour = time.toLocaleTimeString('pt-BR', {
    timeZone: 'America/Sao_Paulo',
  });
  return `${date} ${hour}`;
}

it's to show: // 10/31/22 11:13:25

Cashmere answered 31/10, 2022 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.