Time/Date formats
using moment()
using prototype
using jquery-ui
HTML
<script src="https://raw.github.com/timrwood/moment/2.0.0/min/moment.min.js"></script>
<div class="logPanel">
<label for="fieldClock">Time</label>
<input type="text" id="fieldClock" />
<label for="fieldClock">moment()</label>
<input type="text" id="fieldDateFormat1" class="date" />
<label for="fieldClock">Date.prototype</label>
<input type="text" id="fieldDateFormat2" class="date" />
<label for="fieldClock">$.datepicker.formatDate</label>
<input type="text" id="fieldDateFormat3" class="date" />
</div>
CSS
label { display: block; }
JavaScript
/* http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date/16314504#16314504 */
/* http://stackoverflow.com/questions/16320175/javascript-date-validation-year-and-full-stops/16322386#16322386 */
// Date protoype
Date.prototype.formatTime = function (options) {
var i = 0,
time = [],
len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());
for (; i < len; i += 1) {
var tick = time[i];
time[i] = tick < 10 ? options.pad + tick : tick;
}
return time.join(options.separator);
};
Date.prototype.formatDateField = function (options2) {
var i = 0,
date = [],
len = date.push(this.getDate(), this.getMonth() + 1, this.getFullYear());
for (; i < len; i += 1) {
var chunk = date[i];
date[i] = chunk < 10 ? options2.pad + chunk : chunk;
}
return date.join(options2.separator);
};
// Setup output
var cfg = {
fieldClock: "#fieldClock",
date: ".date",
fieldDate1: "#fieldDateFormat1",
fieldDate2: "#fieldDateFormat2",
fieldDate3: "#fieldDateFormat3",
options: {
pad: "0",
separator: ":",
tick: 1000
},
options2: {
pad: "0",
format: "dd/MM/yy",
separator: "/"
}
};
// Define functionality
function startTime() {
var clock = $(cfg.fieldClock),
fldDate = $(cfg.fieldDate),
now = new Date().formatTime(cfg.options);
clock.val(now);
setTimeout(function () {
startTime();
}, cfg.options.tick);
}
function reformatInput(){
$(cfg.date).blur(function(){
var reformat1 = moment(this.value).calendar(cfg.options2.format),
reformat2 = new Date(this.value).formatDateField(cfg.options2),
reformat3 = $.datepicker.formatDate(cfg.options2.format, new Date(this.value));
$(cfg.fieldDate1).val(reformat1);
$(cfg.fieldDate2).val(reformat2);
$(cfg.fieldDate3).val(reformat3);
});
}
//...