How can I get the current datetime in the format "2014-04-01:08:00:00" in Node?
Seems that there is no good way to do it with original code unless using Regex. There are some modules such as Moment.js though.
If you are using npm:
npm install moment --save
Then in your code:
var moment = require('moment');
moment().format('yyyy-mm-dd:hh:mm:ss');
That may be much easier to understand.
What about:
new Date().toString().replace(/T/, ':').replace(/\.\w*/, '');
Returns for me:
2014-07-14:13:41:23
But the more safe way is using Date
class methods which works in javascript (browser) and node.js:
var date = new Date();
function getDateStringCustom(oDate) {
var sDate;
if (oDate instanceof Date) {
sDate = oDate.getYear() + 1900
+ ':'
+ ((oDate.getMonth() + 1 < 10) ? '0' + (oDate.getMonth() + 1) : oDate.getMonth() + 1)
+ ':' + oDate.getDate()
+ ':' + oDate.getHours()
+ ':' + ((oDate.getMinutes() < 10) ? '0' + (oDate.getMinutes()) : oDate.getMinutes())
+ ':' + ((oDate.getSeconds() < 10) ? '0' + (oDate.getSeconds()) : oDate.getSeconds());
} else {
throw new Error("oDate is not an instance of Date");
}
return sDate;
}
alert(getDateStringCustom(date));
Returns in node.js:
/usr/local/bin/node date.js 2014:07:14:16:13:10
And in Firebug:
2014:07:14:16:14:31
Install moment using
npm install moment --save
And in your code import the moment like this.
var moment = require('moment')
var created = moment().format('YYYY-MM-DD hh:mm:ss')