// Create user jQuery function 'getDate'
(function( $ ){
$.fn.getDate = function(format) {
var gDate = new Date();
var mDate = {
'S': gDate.getSeconds(),
'M': gDate.getMinutes(),
'H': gDate.getHours(),
'd': gDate.getDate(),
'm': gDate.getMonth() + 1,
'y': gDate.getFullYear(),
}
// Apply format and add leading zeroes
return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});
return getDate(str);
};
})( jQuery );
// Usage: example #1. Write to '#date' div
$('#date').html($().getDate("y-m-d H:M:S"));
// Usage: ex2. Simple clock. Write to '#clock' div
function clock(){
$('#clock').html($().getDate("H:M:S, m/d/y"))
}
clock();
setInterval(clock, 1000); // One second
// Usage: ex3. Simple clock 2. Write to '#clock2' div
function clock2(){
var format = 'H:M:S'; // Date format
var updateInterval = 1000; // 1 second
var clock2Div = $('#clock2'); // Get div
var currentTime = $().getDate(format); // Get time
clock2Div.html(currentTime); // Write to div
setTimeout(clock2, updateInterval); // Set timer 1 second
}
// Run clock2
clock2();
// Just for fun
// Usage: ex4. Simple clock 3. Write to '#clock3' span
function clock3(){
var formatHM = 'H:M:'; // Hours, minutes
var formatS = 'S'; // Seconds
var updateInterval = 1000; // 1 second
var clock3SpanHM = $('#clock3HM'); // Get span HM
var clock3SpanS = $('#clock3S'); // Get span S
var currentHM = $().getDate(formatHM); // Get time H:M
var currentS = $().getDate(formatS); // Get seconds
clock3SpanHM.html(currentHM); // Write to div
clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span
setTimeout(clock3, updateInterval); // Set timer 1 second
}
// Run clock2
clock3();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="date"></div><br>
<div id="clock"></div><br>
<span id="clock3HM"></span><span id="clock3S"></span>