javascript date to string
Here is what I need to do.
Get Date, convert to string and pass it over to a third party uti开发者_如何学运维lity. The response from the library will have date in string format as I passed it. So, I need to convert the date to string like 20110506105524 (YYYYMMDDHHMMSS)
function printDate() {
var temp = new Date();
var dateStr = temp.getFullYear().toString() +
temp.getMonth().toString() +
temp.getDate().toString() +
temp.getHours().toString() +
temp.getMinutes().toString() +
temp.getSeconds().toString();
debug (dateStr );
}
The problem with above is that for months 1-9, it prints one digit. How can I change it to print exactly 2 digits for month, date ...
You will need to pad with "0" if its a single digit & note that getMonth
returns 0..11 not 1..12
function printDate() {
const temp = new Date();
const pad = (i) => (i < 10) ? "0" + i : "" + i;
return temp.getFullYear() +
pad(1 + temp.getMonth()) +
pad(temp.getDate()) +
pad(temp.getHours()) +
pad(temp.getMinutes()) +
pad(temp.getSeconds());
}
console.log(printDate());
Relying on JQuery Datepicker, but it could be done easily:
var mydate = new Date();
$.datepicker.formatDate('yy-mm-dd', mydate);
use this polyfill https://github.com/UziTech/js-date-format
var d = new Date("1/1/2014 10:00 am");
d.format("DDDD 'the' DS 'of' MMMM YYYY h:mm TT");
//output: Wednesday the 1st of January 2014 10:00 AM
I like Daniel Cerecedo's answer using toJSON()
and regex. An even simpler form would be:
var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"
A little bit simpler using regex and toJSON()
.
var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]
Which at the time of writing gives you "20151111180924"
.
The good thing of using toJSON()
is that everything comes already padded.
Maybe it is easier to convert the Date into the actual integer 20110506105524
and then convert this into a string:
function printDate() {
var temp = new Date();
var dateInt =
((((temp.getFullYear() * 100 +
temp.getMonth() + 1) * 100 +
temp.getDate()) * 100 +
temp.getHours()) * 100 +
temp.getMinutes()) * 100 +
temp.getSeconds();
debug ( '' + dateInt ); // convert to String
}
When temp.getFullYear() < 1000
the result will be one (or more) digits shorter.
Caution: this wont work with millisecond precision (i.e. 17 digits) since Number.MAX_SAFE_INTEGER is 9007199254740991
which is only 16 digits.
精彩评论