0

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 ?

Hugolpz
  • 17,296
  • 26
  • 100
  • 187
  • 1
    possible duplicate of [Formatting a date in JavaScript](http://stackoverflow.com/questions/1056728/formatting-a-date-in-javascript) – Alexander Feb 18 '13 at 18:20
  • You could use this wonderful Javascript library which really helps dealing with date: [Moment.js](http://momentjs.com/) –  Feb 18 '13 at 18:23
  • Note: SQL format for date is YYYY-MM-DD HH:MM:SS – Hugolpz Feb 18 '13 at 19:15

3 Answers3

3

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);
}
Paul S.
  • 64,864
  • 9
  • 122
  • 138
2

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);
Hugolpz
  • 17,296
  • 26
  • 100
  • 187
  • 1
    You're using `getMilliseconds` and not `getUTCMilliseconds`. It's unlikely the two will differ but you may want to consider keeping everything in _UTC_. – Paul S. Jan 11 '14 at 17:56
0

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.