Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moment.js Sql Date Time Conversion with Nodejs

i am using nodejs to connect to mySql and connection works. while using query such as

SELECT * from someTable

i get the required results. But the problem is that i am having a column which stores date is having the given format. before sending the data i need this format to be converted and vice versa

file_date : Wed Jan 01 2014 05:34:53 GMT+0530 (IST)

This is format i am getting

i am unable to send params with Date in this format from client side so i need to convert this data to "DD-MM-YYYY" format.i need this way so that i can pass params in "DD-MM-YYYY" and fetch data date wise

like image 832
Siddharth Avatar asked Mar 15 '23 06:03

Siddharth


1 Answers

Simple Approach
If you know your date format is supported in Moment, then the simplest approach is to construct a moment object and format it.

var file_date = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var formatted = moment(file_date).format('DD-MM-YYYY');

Deprecation Warning:
However, at some point support for non ISO date formats was deprecated. It will in some cases still work but you should be warned (per the deprecation warning message):

Deprecation warning: value provided is not in a recognized ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non ISO date formats are discouraged and will be removed in an upcoming major release.

Workaround
Instead, if you know the format of an input string, you can use that to parse a moment.

var s = 'Wed Jan 01 2014 05:34:53 GMT+0530 (IST)';
var m = moment(s, 'ddd MMM DD YYYY hh:mm:ss [GMT]ZZ').format('MM-DD-YYYY');
console.log(m);
<script src="https://momentjs.com/downloads/moment.min.js"></script>

When specifying a format manually like this, it helps to have the format documentation handy: https://momentjs.com/docs/#/displaying/format/

like image 69
ThisClark Avatar answered Mar 27 '23 07:03

ThisClark