I have a node.js application, I used Typescript to build my server, now I need to format dates posted to my server to yyyy-mm-dd format. I could do it in Javascript by using Moment.js but as I used Typescript, I could not figure it out how to convert a date string to yyyy-mm-dd so I can post data to database.
Asked
Active
Viewed 1,503 times
0
-
Does this answer your question? [How to format a UTC date as a \`YYYY-MM-DD hh:mm:ss\` string using NodeJS?](https://stackoverflow.com/questions/10645994/how-to-format-a-utc-date-as-a-yyyy-mm-dd-hhmmss-string-using-nodejs) – Dec 03 '19 at 19:04
-
You should be able to use moment in type script.. Just use `Import * as moment from 'moment'` instead of require. – caden311 Dec 03 '19 at 19:10
-
could you provide a simple code, because I tried it did not worked – Dec 03 '19 at 19:40
1 Answers
0
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);
}
}
}

MJ X
- 8,506
- 12
- 74
- 99