user2023370
user2023370

Reputation: 11037

Different time format returned by toLocaleTimeString

I am using Javascript code such as that shown below, and recently found that while Date.prototype.toLocaleTimeString() on one machine appends " GMT" or " BST" (depending on the time of year); on another machine, nothing is appended.

var m = new Date();
var time = m.toLocaleTimeString();

I use the returned string to create a log file, and would like the file names to have a canonical structure. I don't mind which of the two string formats is returned, as long as it is the same on both machines.

By the way, I also tried providing first and second arguments, such as m.toLocaleTimeString('en-gb', { hour: '2-digit', minute: '2-digit', second: '2-digit' }), or m.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' }), but then the seconds are no longer included in the returned string.

Upvotes: 0

Views: 139

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30675

You could create a custom format function for your logs, using the Date.getHours(), getMinutes() etc.

This should be consistent across platforms and would allow any customization to be added easily.

function formatTimestamp(date) {
    const hms = [date.getHours(), date.getMinutes(), date.getSeconds()];
    return hms.map(s => (s + '').padStart(2, '0')).join(':');
}

console.log('Timestamp:', formatTimestamp(new Date())); 

Upvotes: 1

Related Questions