I am looking for a simple jQuery clock.
There are tonnes out there, but I am looking for one where I can set the current time, and the output format.
So I want to be able to call something like
$('#clock').clock({
format: 'l dS F Y, h:i a', //PHP date format, but anything that can mimic this output is good
date: '2012-07-01 23:59:59' //MYSQL date format, but can output as anything
});
Is there something like this (even raw js will do).
Creating a counter for a clock is pretty simple, you can probably write one in less time that it takes to review the answers you'll get here. Below is one I made as an example of prototype inheritance.
Just format the output however you like, add CSS to your hearts content to make it look good.
// Create a digital clock
// Write time in hh:mm:ss.nnn format
// el is an element
function Clock(el) {
if (typeof el == 'string') el = document.getElementById(el);
this.el = el;
}
// Clock methods
Clock.prototype = {
// Utilty functions
addZ: function(n) {
return n < 10? '0' + n : '' + n;
},
addZZ: function(n) {
return n < 10? '00' + n : n < 100? '0' + n : '' + n;
},
formatTime: function(d) {
return this.addZ(d.getHours()) +
':' + this.addZ(d.getMinutes()) +
':' + this.addZ(d.getSeconds()) +
// Milliseconds are just for debug, remove from finished version
'.' + this.addZZ(d.getMilliseconds())
},
update: function() {
var clock = this;
var d = new Date();
// Set next run to just after full second
var interval = 1020 - d.getMilliseconds()
this.el.innerHTML = this.formatTime(d);
setTimeout(function(){
clock.update();
}
,interval);
}
};
// Create a new clock
// el is id or element to display text in
function newClock(el) {
var y = new Clock(el);
y.update();
}
Edit
A generic date format function: http://blog.stevenlevithan.com/archives/date-time-format
A specific function to format a date to be like Tuesday 05th July 2011, 10:31 am:
var formatDate = (function() {
// Days of the week, zero is Sunday
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
// Months of the year, zero is January
var months = ['January','February','March','April',
'May','June','July','August','September',
'October','November','December'];
// Format single digit numbers
function addZ(n) {
return n<10? '0' + n : '' + n;
}
// Add ordinal to numbers
function addOrdinal(n) {
return ['th','st','nd','rd'][(''+n).slice(-1)] || 'th';
}
return function (date) {
var d = addZ(date.getDate());
var h = date.getHours();
var ap = h < 12? 'am' : 'pm';
h = addZ(h > 12? h - 12 : h);
return days[date.getDay()] + ' '
+ d + addOrdinal(d) + ' '
+ months[date.getMonth()] + ' '
+ date.getFullYear() + ', '
+ h + ':'
+ addZ(date.getMinutes()) + ' '
+ ap
}
}());
Related
I am creating a time slot in Javascript. Please no jQuery. If you put the first time and last time, then it will make a lists of interval and after 12 number, it will change to am to pm. Suppose, if your start time is 11 and end time is 19, then it will make a slot like like this,
11AM-12PM
12PM-1PM
1PM-2PM
2pm-3pm
3pm-4pm
4pm-5pm
5pm-6pm
6pm-7pm
But, problem is I am taking it as simple integer and giving for loop. I want hold the 24 hrs format of it, like for
1PM-2PM
it should take this value in any variable which will send to server
13:00:00 - 14:00:00
Here is my JS code.
getTimeValues: function() {
console.log('here i am');
var timeValues = this.timeValues;
var minTime = 11; //vary this to change the first
var maxTime = 19; //vary this to chage the
var string;
for (var i = minTime; i < maxTime; i++) {
if(i<12) {
lowersuffix = 'AM';
startRange = i;
}
else if(i===12){
lowersuffix = 'PM';
startRange = i;
}
else {
lowersuffix = 'PM';
startRange = i - 12;
}
if((i+1)<12) {
uppersuffix = 'AM';
endRange = (i+1);
}
else if((i+1)===12){
uppersuffix = 'PM';
endRange = (i+1);
}
else {
uppersuffix = 'PM';
endRange = (i+1) - 12;
}
string = startRange + lowersuffix + '-' + endRange + uppersuffix;
console.log(string);
timeValues.push(string);
};
},
Are you looking for this?
for (var i = minTime; i < maxTime; i++) {
string = i + ':00:00 - ' + (i+1) + ':00:00';
console.log(string);
timeValues.push(string);
};
It seems you're after a simple function to convert time in am/pm format to 24hr format. The following should do the job, hopefully the comments are sufficient. If not, ask.
/* #param {string} time - time string in hh:mm:ss am/pm format
** - missing time parts are treated as 0
** #returns {string} time in 24hr format: hh:mm:ss
**/
function to24hrTime(time) {
// Get the digits from the string
var b = time.match(/\d+/g);
// Test whether it's am or pm, default to am
var pm = /pm$/i.test(time);
var h, m, s;
// If no digits were found, return undefined
if (!b) return;
// Otherwise, convert the hours part to 24hr and two digits
h = ('0' + ((pm? 12:0) + (b[0]%12))).slice(-2);
// Convert minutes part to two digits or 00 if missing
m = ('0' + (b[1] || 0)).slice(-2);
// Convert seconds part to two digits or 00 if missing
s = ('0' + (b[2] || 0)).slice(-2);
// Return formatted string
return h + ':' + m + ':' + s;
}
document.write(
to24hrTime('3:15pm') + '<br>' +
to24hrTime('3:15am') + '<br>' +
to24hrTime('11am') + '<br>' +
to24hrTime('11pm') + '<br>' +
to24hrTime('12AM') + '<br>' +
to24hrTime('12PM') + '<br>' +
to24hrTime('11 pm') + '<br>' +
to24hrTime('12 AM') + '<br>' +
to24hrTime('12 PM')
);
setInterval(function(){
var ss = "<?php echo Date('Y-m-d H:i:s'); ?>";
console.log(ss);
}, 1000);
I have this little code. It takes Date one time and then all the time, result is the same.
(12) 2014-10-19 19:42:54
How can I fix it?
If you're trying to have a clock that increases by the second just like any other clock, you're gonna have to use javascript to implement it and you generally don't even need PHP to do it.
Edited answer to use server time
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
var today=new Date('<?php print date("F d, Y H:i:s", time())?>');
function setTime() {
today.setSeconds(today.getSeconds()+1)
var year=today.getFullYear();
var month=today.getMonth();
var day=today.getDate();
var hour=today.getHours();
var minute=today.getMinutes();
var second=today.getSeconds();
minute = checkTime(minute);
second = checkTime(second);
month = checkTime(month);
var time = year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
console.log(time);
}
setInterval(startTime, 1000);
Try this:
var unixtime = <?=date('U')?>;
setInterval(function()
{
var date = new Date();
date.setTime(++unixtime * 1000);
var ss = date.getFullYear() + '-'
+ (date.getMonth() < 9 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + '-'
+ (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' '
+ (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':'
+ (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':'
+ (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
console.log(ss);
}, 1000);
Open rendered page source and you will see that resulted HTML looks something like this:
<script>
setInterval(function(){
var ss = "2014-10-19 20:52:12";
console.log(ss);
}, 1000);
</script>
PHP script is a server side program that outputs some HTML, which browser renders. So there is no surprise that you are facing this behavior.
If you want to create a timer in javasctipt you need to use Date object instance:
setInterval(function() {
var d = new Date(),
ss = d.getFullYear() + '-' + d.getMonth(); // etc.. formate you date
console.log(ss);
}, 1000);
Refer Date documentation for available methods.
You have to update your date in JavaScript in each setInterval call.
When you produce static code using php it defines JavaScript function with fixed value of date. Body of this function isn't overrided after each call, because there is generated specific date.
I have written some Javascript to convert a database datetime in UTC format into local datetime. It works fine in Firefox and IE, but does not work in Chrome (for some reason it adds 3 hours to the times). Here is my code, any advice would be very appreciated :)
EDIT : The datetime is passed into my first function in the format '2014-06-21 20:00:00'
function convertUTCTimeToLocal(utc24HrDateTime) {
//first convert from 24hr to 12hr clock
var twentyFourHrTime = convertDateToTime(utc24HrDateTime);
var twelveHrTime = convert24hrTo12Hr(twentyFourHrTime);
var twelveHrDateTime = convert12HrToDateTime(utc24HrDateTime, twelveHrTime);
var utc12HrDateTime = twelveHrDateTime + ' UTC';
var date = new Date(utc12HrDateTime);
var dayMonthTimeOnly = convertToDayMonthTimeOnly(date);
return dayMonthTimeOnly;
}
function convert24hrTo12Hr(time) {
// Check correct time format and split into components
time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
if (time.length > 1) { // If time format correct
time = time.slice(1); // Remove full string match value
time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
time[0] = +time[0] % 12 || 12; // Adjust hours
}
return time.join(''); // return adjusted time or original string
}
function convertDateToTime(fixtureDate) {
var d = new Date(fixtureDate); // now
var y = d.getFullYear(); // the full year (4 digits)
var m = d.getMonth() + 1; // 0-based month
var dt = d.getDate(); // 0-based day of the month
dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10
var h = d.getHours(); // 0-based hours
h = h < 10 ? '0' + h : h; // add a preceding 0 to numbers less than 10
var mn = d.getMinutes(); // minutes
mn = mn < 10 ? '0' + mn : mn; // add a preceding 0 to numbers less than 10
return h + ':' + mn;
}
function convert12HrToDateTime(fixtureDate, twelveHrTime) {
var d = new Date(fixtureDate); // now
var y = d.getFullYear(); // the full year (4 digits)
var m = d.getMonth() + 1; // 0-based month
var dt = d.getDate(); // 0-based day of the month
dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10
return m + '/' + dt + '/' + y + ' ' + twelveHrTime;
}
function convertToDayMonthTimeOnly(fixtureDate) {
var d = new Date(fixtureDate); // now
var y = d.getFullYear(); // the full year (4 digits)
var m = d.getMonth() + 1; // 0-based month
var dt = d.getDate(); // 0-based day of the month
dt = dt < 10 ? '0' + dt : dt; // add a preceding 0 to numbers less than 10
var h = d.getHours(); // 0-based hours
h = h < 10 ? '0' + h : h; // add a preceding 0 to numbers less than 10
var mn = d.getMinutes(); // minutes
mn = mn < 10 ? '0' + mn : mn; // add a preceding 0 to numbers less than 10
return dt + '/' + m + ' ' + h + ':' + mn;
}
Looking at the data returned from the ajax call in the page http://brasil2014.azurewebsites.net/Team/Brazil I was able to reproduce the observation using the following test (written using QUnit):
test("convertUTCTimeToLocal", function(assert) {
var expected = "12/6 22:00",
actual = convertUTCTimeToLocal("2014-06-12T20:00:00");
assert.equal(actual, expected);
});
(My time zone is GMT+1, but with daylight savings, hence I am expecting the time to be offset +2 hours).
I was able to further drill down the problem using the following test case:
test("convertDateToTime", function(assert) {
var expected = "20:00",
actual = convertDateToTime("2014-06-12T20:00:00");
assert.equal(actual, expected);
});
Changing the first lines of the function convertDateToTime to:
function convertDateToTime(fixtureDate) {
var d = new Date(fixtureDate); // now
console.log(d);
...
}
showed me that the value of d already was converted from UTC to local time.
Some investigation showed that the underlying cause is the fact that JavaScript engines are free to interpret the date in any timezone it wants. See the following answer for more details.
Using this knowledge I rewritten and simplified the the code as follows:
function convertUTCTimeToLocal(fixtureDate) {
function zeroPad(num) {
return num<10 ? '0'+num : num;
}
var d = new Date(fixtureDate + "Z"),
m = d.getMonth() + 1,
dt = zeroPad(d.getDate()),
h = zeroPad(d.getHours()),
mn = zeroPad(d.getMinutes());
return dt + '/' + m + ' ' + h + ':' + mn;
}
The following test case shows that it works correctly on both Chrome and Firefox:
test("convertUTCTimeToLocal", function(assert) {
var expected = "12/6 22:00",
actual = convertUTCTimeToLocal2("2014-06-12T20:00:00");
assert.equal(actual, expected);
})
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 ?
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);
}
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);
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.
Looking for a creative way to be sure values that come from the getHours, getMinutes, and getSeconds() method for the javascript Date object return "06" instead of 6 (for example). Are there any parameters that I don't know about? Obviously I could write a function that does it by checking the length and prepending a "0" if need be, but I thought there might be something more streamlined than that.
Thanks.
Similar to #jdmichal's solution, posting because I'd prefer something a little shorter:
function pad(n) { return ("0" + n).slice(-2); }
pad(6); // -> "06"
pad(12); // -> "12"
Rather than add individual methods to Date.prototype, you could just add this method to Number.prototype:
Number.prototype.pad = function (len) {
return (new Array(len+1).join("0") + this).slice(-len);
}
// Now .pad() is callable on any number, including those returned by
var time = date.getHours().pad(2) + ":"
+ date.getMinutes().pad(2) + ":"
+ date.getSeconds().pad(2);
Update: ECMAScript 2017 (ECMA-262)
padStart has been added to pad the beginning of a string with another string, where the first value is the length it should be and the second value being what to pad it with.
For example:
let d = new Date()
let h = `${d.getHours()}`.padStart(2, '0')
let m = `${d.getMinutes()}`.padStart(2, '0')
let s = `${d.getSeconds()}`.padStart(2, '0')
let displayDate = h + ":" + m + ":" + s
// Possible Output: 09:01:34
Pre-ECMAScript 2017
As far as I know, there's not. And I do this all the time for converting dates to the XML dateTime format.
It's also important to note that those methods you list return a number, not a string.
You can, of course, add these yourself by modifying Date.prototype.
Date.prototype.getHoursTwoDigits = function()
{
var retval = this.getHours();
if (retval < 10)
{
return ("0" + retval.toString());
}
else
{
return retval.toString();
}
}
var date = new Date();
date.getHoursTwoDigits();
function pad2(number) {
return (number < 10 ? '0' : '') + number
}
document.write(pad2(2) + '<br />');
document.write(pad2(10) + '<br />');
OUTPUT:
02
10
Ok so heres my solution
function pad(n) {
return ((n <= 9 && n >= 0) ? "0":"") + n.toString();
}