1

I want to the current date/time formatted in this format:

year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;

Currently I'm doing it as such. Is there a more elegant approach without the use of external libraries like moment.js?

var now     = new Date(); 
var year    = now.getFullYear();
var month   = now.getMonth()+1; 
var day     = now.getDate();
var hour    = now.getHours();
var minute  = now.getMinutes();
var second  = now.getSeconds(); 
var milli   = now.getMilliseconds();

if(month.toString().length == 1) {
var month = '0'+month;
}
if(day.toString().length == 1) {
var day = '0'+day;
}   
if(hour.toString().length == 1) {
var hour = '0'+hour;
}
if(minute.toString().length == 1) {
var minute = '0'+minute;
}
if(second.toString().length == 1) {
var second = '0'+second;
}   
if(milli.toString().length == 1) {
var milli = '0'+milli;
}   
var m_session_startTime =  year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second+':'+milli;
etayluz
  • 15,920
  • 23
  • 106
  • 151
  • 4
    Are you able to use an external library such as moment.js? – basic Jul 24 '18 at 20:08
  • 2
    `month = ('0'+month).substr(-2);` etc. – Teemu Jul 24 '18 at 20:08
  • 2
    Well, you could use [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) instead of concatenation, also [`padStart()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart). – zero298 Jul 24 '18 at 20:09
  • You should not be using `var` when reassigning the variables value. – epascarello Jul 24 '18 at 20:13
  • Could also check out [toLocaleString](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString) has a lot of options and built in in most browsers – SuperPrograman Jul 24 '18 at 20:13
  • If you got the same pattern over and over it might be benefitial to wrap it into a function – Jonas Wilms Jul 24 '18 at 20:13
  • look into [`padStart()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart) – epascarello Jul 24 '18 at 20:13
  • I seriously can't be the only person who thinks moment js is great, but people should stop just recommending the library instead of explaining a solution. – zfrisch Jul 24 '18 at 20:15
  • @zfrisch How is recommending a library that does exactly what you want to do not explaining a solution? – basic Jul 24 '18 at 20:17
  • @basic Mentioning it is fine, but I see too many answers that say "oh just use moment!" without even defining a solution with the library. Yes, it's a great tool, but by telling everyone to simply rely on it you're abstracting. If anyone has a problem in Vanilla JS we don't just say "oh use JQuery!" because that's ridiculous. It's just my opinion, but if I for instance asked how to build a server in node, I don't want someone to say "grab express", I want someone to explain the http module and mention express as an aside. – zfrisch Jul 24 '18 at 20:28
  • 1
    @zfrisch oh I absolutely agree there, if you notice I added a solution to accompany the comment. I agree, all too many times I see hey use this lib without saying how to use it. – basic Jul 24 '18 at 20:30

4 Answers4

0

Use a moment.js. Great library that is designed to exactly what you would like. You can use the .format option.

var now = moment().format('YYYY-MM-DD HH:mm:ss.SSS');
$('#timeval').text(now);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Current Time: <br>
<a id="timeval"></a>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

https://momentjs.com/

Altay Akkus
  • 325
  • 1
  • 10
basic
  • 3,348
  • 3
  • 21
  • 36
0

Leverage template literals instead of concatenation and padStart() to fill leading zeros.

const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, "0");
const day = String(now.getDate()).padStart(2, "0");
const hour = String(now.getHours()).padStart(2, "0");
const minute = String(now.getMinutes()).padStart(2, "0");
const second = String(now.getSeconds()).padStart(2, "0");
const milli = String(now.getMilliseconds()).padStart(4, "0");

const m_session_startTime = `${year}-${month}-${day} ${hour}:${minute}:${second}:${milli}`;
console.log(m_session_startTime);
zero298
  • 25,467
  • 10
  • 75
  • 100
  • Can you build on NotoriousPyro's answer? His is the most elegant of them all but it doesn't have the correct formatting. – etayluz Jul 24 '18 at 20:29
  • 1
    @etayluz That's the thing, their answer just dumps the String that is returned by `toJSON()`. It can't be improved without **really** terse String parsing and manipulation. If you want the most flexibility, you have to get all the properties out through the methods as you were doing at the start and then mash them together. – zero298 Jul 24 '18 at 20:32
0

Try this?

let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");

console.log(jsonDate);

>  2018-07-24 20:32:06:435

Alternatively, if you want to split the entire thing into substrings:

let date = new Date();
let jsonDate = date.toJSON();
jsonDate = jsonDate.replace(/[TZ]/g, " ");
jsonDate = jsonDate.replace(/\./g, ":");
let dateTime = jsonDate.split(" ");
let dt = dateTime[0].split("-");
let tt = dateTime[1].split(":");
let year = dt[0];
let month = dt[1];
let day = dt[2];
let hour = tt[0];
let minute = tt[1];
let second = tt[2];
let mili = tt[3];

console.log(jsonDate);
console.log(dateTime[0]);
console.log(dateTime[1]);
console.log([year, month, day, hour, minute, second, mili].join("~"));
console.log("Date: " + [year, month, day].join("-") + " Time: " + [hour, minute, second, mili].join(":"));

> 2018-07-24 21:03:05:706 
> 2018-07-24
> 21:03:05:706
> 2018~07~24~21~03~05~706
> Date: 2018-07-24 Time: 21:03:05:706

As you might have noticed from this response, I work with databases. I have heavy bash, javascript, php, sql, golang background.

NotoriousPyro
  • 526
  • 3
  • 16
0

You could use moment.js, it really helps you with formatting dates.

console.log(moment().format('YYYY-MMMM-DD h:mm:ss:SSS'));
<script src="https://momentjs.com/downloads/moment.min.js"></script>

This command does the job pretty well. moment() is a date object, when there are no arguments given like in this example it takes the current time but you can also use moment("2018-12-4") for specific dates.

You can then format the date according to your need,

YYYY is the full year (2018)

MMMM is the full month name (July)

(you can also use MMM for the short version of the month name)

DD is the day as a number (24)

(you can also use dddd for the full name of the day or ddd for the short name)

h is the hour as number (22)

mm is the minute as a number (23)

ss is the second as a number (as an example 22)

SSS is the millisecond as a number (example 245)

Altay Akkus
  • 325
  • 1
  • 10