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.
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')
);
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);
})
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
}
}());
I have two values that are used for the amount of time it will take to complete a task. How can I add these values together to come up with a total number of hours and minutes, but still have the value account for 60 minutes equalling one hour?
The two values I'd like to get the sum of and the total value are in HH:MM (00:00) format.
Thanks!
Writing your own time and date functions can get complex. Why re-invent the wheel. Take a look at the excellent http://www.datejs.com/ date library. It handles all date and time related tasks and usage is very simple.
Here's something I had laying around. It allows for an infinite number of arguments, so you could have addTime('01:00') or addTime('01:00', '02:00', '03:00', '04:00'), etc. It's three functions long because it also verifies if the times entered are properly formatted, and if not, then it formats them. (E.g. Ensures that minutes is 2 digits long, and if hours is 1 digit long, then pad it with one zero, etc.)
You can play with it here: http://jsfiddle.net/WyxwU/
It's also here:
var totalTime = addTime('12:34', '56:12', '78:45');
document.write(totalTime);
function addTime()
{
if (arguments.length < 2)
{
if (arguments.length == 1 && isFormattedDate(arguments[0])) return arguments[0];
else return false;
}
var time1Split, time2Split, totalHours, totalMinutes;
if (isFormattedDate(arguments[0])) var totalTime = arguments[0];
else return false;
for (var i = 1; i < arguments.length; i++)
{
// Add them up
time1Split = totalTime.split(':');
time2Split = arguments[i].split(':');
totalHours = parseInt(time1Split[0]) + parseInt(time2Split[0]);
totalMinutes = parseInt(time1Split[1]) + parseInt(time2Split[1]);
// If total minutes is more than 59, then convert to hours and minutes
if (totalMinutes > 59)
{
totalHours += Math.floor(totalMinutes / 60);
totalMinutes = totalMinutes % 60;
}
totalTime = totalHours + ':' + padWithZeros(totalMinutes);
}
return totalTime;
}
function isFormattedDate(date)
{
var splitDate = date.split(':');
if (splitDate.length == 2 && (parseInt(splitDate[0]) + '').length <= 2 && (parseInt(splitDate[1]) + '').length <= 2) return true;
else return false;
}
function padWithZeros(number)
{
var lengthOfNumber = (parseInt(number) + '').length;
if (lengthOfNumber == 2) return number;
else if (lengthOfNumber == 1) return '0' + number;
else if (lengthOfNumber == 0) return '00';
else return false;
}
Here is the simple JS code for this,
var a = "2:50";
var b = "2:15";
var splitTimeStr = function(t){
var t = t.split(":");
t[0] = Number(t[0]);
t[1] = Number(t[1]);
return t;
};
var addTime = function(t1, t2){
var t1Hr = splitTimeStr(t1)[0];
var t1Min = splitTimeStr(t1)[1];
var t2Hr = splitTimeStr(t2)[0];
var t2Min = splitTimeStr(t2)[1];
var rHr = t1Hr + t2Hr;
var rMin = t1Min + t2Min;
if (rMin >= 60)
{
rMin = rMin - 60;
rHr = rHr + 1;
}
if (rMin < 10) rMin = "0" + rMin;
if (rHr < 10) rHr = "0" + rHr;
return "" + rHr + ":" + rMin;
};
document.write(addTime(a, b));
you can validate/play this with code here: http://jsfiddle.net/z24v7/
What you have to do is calculate them to a decimal by that I mean.
Strip out the hour/mins multiple that by 60 + to mins
//strip out the hours
l_hour = Number(l_time$.substr(0, l_pos));
//Strip out the mins
l_min = Number(l_time$.substr(l_pos + 1, l_time$.length));
//add the two values divided by 60 mins
l_time_decimal= Number(Math.abs(l_hour)) + Number(Math.abs(l_min)/60);
Do this for each value then deduct the two figures to give you the difference (i.e time taken). All thats left is convert it back from a decimal to a time
l_difference_in_min = l_difference * 60;
l_time_mins = l_difference_in_min%60;
l_time_hours = (l_difference_in_min - l_mins)/60;
Now just format the two to be HH:MM
I would break the problem into sub-tasks that are reusable. You have to concerns here:
Process a time string in "hh:mm" format: Converting this to minutes makes sense because it seems to be the time granularity at which you're operating.
Format a given number of minutes into a time string in "hh:mm" format.
The fact that you're adding two times together is a diversion from the actual two problems above.
Parse a time string into minutes:
function parseMinutes(s) {
var tokens = s.split(":");
return tokens[0] * 60 + parseInt(tokens[1]);
}
Format minutes into a time string:
function formatMinutes(minutes) {
function pad(n) {
return n > 9
? n
: ("0" + n);
}
var hours = Math.floor(minutes / 60),
mins = minutes % 60;
return pad(hours) + ":" + pad(mins);
}
Then your specific problem can be tackled by:
var sum = formatMinutes(parseMinutes(a) + parseMinutes(b));
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();
}