JS - formatting a datetime value
I'm trying to format the current datetime into the following format: yyyyMMdd_hhmmss as part of a file download process (the file downloaded will get time stamped with the above value in the name).
in the JS I have this:
new Date().toString("yyyyMMdd_hhmmss");
In the results I'm getting this: Fri_Jul_07_2017_113038_GMT-0400_(Eastern_Daylight_Time)
Woaza! That's way more than I asked for! Bleh. Everything I've looked up uses one library or another. I'm working within the confines of an application, so adding another library isn't a viable option as I don't have the chance to include any thing.
-tg
Re: JS - formatting a datetime value
I think in JS to get what you want you basically have to use all the individual functions e.g. Date. + getFullYear() , getMonth() , getDate(), getHours() , getMinutes() , getSeconds() and concatenate them all together.
also for some unknown reason in JS you have to add 1 to the Month, and you will probably have to format the output of each of those functions to your required number of digits !
Re: JS - formatting a datetime value
Yeah, in the end, that's what I ended up doing... kind of a pain in the arse, but it got the job done. I just couldn't see the point of pulling in a whole library just for a single line like this.
javascript Code:
var currentdate = new Date();
b = "samplefile_" + currentdate.getFullYear() +
((currentdate.getMonth() < 10) ?"0":"") + (currentdate.getMonth()+1) +
((currentdate.getDate() < 10) ?"0":"") + currentdate.getDate() + "_" +
((currentdate.getHours() < 10) ?"0":"") + currentdate.getHours() +
((currentdate.getMinutes() < 10) ?"0":"") + currentdate.getMinutes() +
((currentdate.getSeconds() < 10) ?"0":"") + currentdate.getSeconds() + ".txt"
-tg
Re: JS - formatting a datetime value
Yep you would have thought that something as simple as that would be built in a bit more elegantly and not make you rely on library's to have a nice way to do it.
Re: JS - formatting a datetime value
Sorry to resurrect and older post, but this seems silly to me. I wonder if formatting date/time Strings was an oversight or intentionally left out because this seems like a basic function of a scripting language.
Edit - Also, I tested this that works without having to use so many ternary if statements:
Code:
function yyyyMMdd_hhmmss(d) {
var arrDate = d.toString().split(/ |:/);
var yyyy = arrDate[3];
var MM = ((d.getMonth() < 10) ? "0": "") + (d.getMonth()+1);
var dd = arrDate[2];
var hh = arrDate[4];
var mm = arrDate[5];
var ss = arrDate[6];
return yyyy + MM + dd + '_' + hh + mm + ss;
}