How to Format a Utc Date as a 'Yyyy-Mm-Dd Hh:Mm:Ss' String Using Nodejs

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

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).

Javascript Date Now (UTC) in yyyy-mm-dd HH:mm:ss format

We should use in-built toISOString function to covert it to ISO date format and remove not required data using string manipulation.

let datenow = new Date();

console.log(datenow); // "2021-07-28T18:11:11.282Z"
console.log(generateDatabaseDateTime(datenow)); // "2021-07-28 14:11:33"

function generateDatabaseDateTime(date) {
return date.toISOString().replace("T"," ").substring(0, 19);
}

Format JavaScript date as yyyy-mm-dd

You can do:

function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();

if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;

return [year, month, day].join('-');
}

console.log(formatDate('Sun May 11,2014'));

How to get IST date time (YYYY-MM-DD HH:mm:ss) in node js?

Install moment package and write the following two lines code to solve the problem:

var moment = require('moment');
console.log(moment().format("YYYY-MM-DD HH:mm:ss"));

Convert UTC date time to local date time

Append 'UTC' to the string before converting it to a date in javascript:

var date = new Date('6/29/2011 4:52:48 PM UTC');
date.toString() // "Wed Jun 29 2011 09:52:48 GMT-0700 (PDT)"

Format Date as yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Call the toISOString() method:

var dt = new Date("30 July 2010 15:05 UTC");
document.write(dt.toISOString());

// Output:
// 2010-07-30T15:05:00.000Z

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

[Addendum 12/2022]: Here's a library to format dates using Intl.DateTimeFormat.

Try something like this

var d = new Date,
dformat = [d.getMonth()+1,
d.getDate(),
d.getFullYear()].join('/')+' '+
[d.getHours(),
d.getMinutes(),
d.getSeconds()].join(':');

If you want leading zero's for values < 10, use this number extension

Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
// usage
//=> 3..padLeft() => '03'
//=> 3..padLeft(100,'-') => '--3'

Applied to the previous code:

var d = new Date,
dformat = [(d.getMonth()+1).padLeft(),
d.getDate().padLeft(),
d.getFullYear()].join('/') +' ' +
[d.getHours().padLeft(),
d.getMinutes().padLeft(),
d.getSeconds().padLeft()].join(':');
//=> dformat => '05/17/2012 10:52:21'

See this code in jsfiddle

[edit 2019] Using ES20xx, you can use a template literal and the new padStart string extension.

const dt = new Date();
const padL = (nr, len = 2, chr = `0`) => `${nr}`.padStart(2, chr);

console.log(`${
padL(dt.getMonth()+1)}/${
padL(dt.getDate())}/${
dt.getFullYear()} ${
padL(dt.getHours())}:${
padL(dt.getMinutes())}:${
padL(dt.getSeconds())}`
);

How to convert a date to yyyy-mm-dd in typescript

Create a class name it dateformater.ts or whatever you like

export class Dateformater{
formatDate(date){
let pubdate = new Date(date).toISOString().
replace(/T/, ' '). // replace T with a space
replace(/\..+/, '');
return pubdate;
}
}

import it in your ts file where you call your db functions to insert data to database

   import {Dateformater} from '../../lib/dateformate/dateformat.formate';

export class MyClass{
private _dateformater = new Dateformater();

async insertData(body):Promise<any>{
try{
//console.log(this._dateformater.formatDate(body.publishdate));
let pubdate = new Date(this._dateformater.formatDate(body.publishdate));

const pool = await poolPromise;
const request = await pool.request()
.input('Title',TYPES.VarChar,body.title)
.input('StatusID',TYPES.Int,body.StatusID)
.input('Publishdate',TYPES.DateTime,pubdate)

let dyQuery = `INSERT INTO Tablename
(Title, TestID, Publishdate)
VALUES
(@Title, @StatusID, @Publishdate)`;
const result = await request.query(dyQuery);
//const result = await request.query(CustomQuery);
return result.rowsAffected;
}catch(err){
this.logger.StartLogger().error(err);
}
}
}

Get String in YYYYMMDD format from JS date object?

Altered piece of code I often use:

Date.prototype.yyyymmdd = function() {
var mm = this.getMonth() + 1; // getMonth() is zero-based
var dd = this.getDate();

return [this.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('');
};

var date = new Date();
date.yyyymmdd();

Get UTC date time by Date and time Zone name

I would use a library like Day.js for this purpose. You can parse in the date and time in a timezone, convert to UTC, then display in the desired format.

dayjs.extend(utc);
dayjs.extend(timezone);
dayjs.extend(customParseFormat);

function getUTCDateTime(date, time, timeZoneName) {
const utcDate = dayjs
.tz(`${date} ${time}`, "YYYY-MM-DD HH:mm", timeZoneName)
.utc()
.format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]");
return utcDate;
}


Related Topics



Leave a reply



Submit