Reputation: 18258
When I click my
<button id="A">Hello!</button>
I want to fire my function clickButton() but also get a military date style timestamp YYYYMMDDHHMMSSXXX for the exact time when the button was clicked. How can I do in JS or better, JQuery ?
Upvotes: 0
Views: 1292
Reputation: 18258
Fork of Paul S. answer including millisecs (fiddle):
//makeStamp: Create a timestamp with format YYYYMMDDhhmmssxxx
function makeStamp(d) { // Date d
// Get date's subparts as variables:
var y = d.getUTCFullYear(), // 4 digits
M = d.getUTCMonth() + 1,// 1-2 digits
D = d.getUTCDate(), // 1-2 digits
h = d.getUTCHours(), // 1-2 digits
m = d.getUTCMinutes(), // 1-2 digits
s = d.getUTCSeconds(); // 1-2 digits
ms = d.getUTCMilliseconds();// 1-3 digits
// 2. Adjust lengths to be right:
function l2(x) { // for months, days, hours, seconds. Force length=2 digits.
x = x + ''; // stingify
if (x.length === 1) { return '0' + x; }
return x;
}
function l3(x) { // for milliseconds. Force length=3 digits
x = x + ''; // stingify
if (x.length === 1) { return '00' + x; }
if (x.length === 2) { return '0' + x; }
return x;
}
// Concatenate to YYYYMMMDDDhhmmssxxx format:
return y + l2(M) + l2(D) + l2(h) + l2(m) + l2(s) + l3(ms);
}
var c = makeStamp(new Date());
alert('Time on run was: ' + c);
Upvotes: 2
Reputation: 1931
If the format is not fixed and only care about the exact time your button was clicked, you can simply use toString()
If you need further flexibility and need a lot of dates management in JS, make sure you checkout Datejs. It's quite impressive and well documented as you can see in case of the toString function.
Upvotes: 0
Reputation: 66334
Just pad and stick together
function makeStamp(d) { // Date d
var y = d.getUTCFullYear(),
M = d.getUTCMonth() + 1,
D = d.getUTCDate(),
h = d.getUTCHours(),
m = d.getUTCMinutes(),
s = d.getUTCSeconds(),
pad = function (x) {
x = x+'';
if (x.length === 1) {
return '0' + x;
}
return x;
};
return y + pad(M) + pad(D) + pad(h) + pad(m) + pad(s);
}
Upvotes: 3