In my javascript iam using GetHour and GetMinutes function.For eg:Current Time is 2:03.If in this case i use GetHour(),it returns 2.Instead i need 02.Can anybody help?
var hour = GetHour() < 10 ? '0' + GetHour() : GetHour();
var d,h
d = new Date()
h = (h = d.getHours()) < 10 ? '0' + h : h
The obvious answer is to use an IF statement...
var dat = new Date();
var hr = dat.getHour();
if(hr < 10) {
hr = "0" + hr;
}
You could always just do
var time = new Date();
('0' + time.getDate()).slice(-2)
There's a javascript library here which looks like it will handle all sorts of date conversions nicely, including formatting dates so that the month is always two digits.
If you use the Prototype framework there's a toPaddedString method that does this.
a = 2;
a.toPaddedString(2)
// results in "02"
There is no function for that.
Use the following to add a leading 0:
var date = new Date();
var hours = new String(date.getHours());
if (hours.length == 1)
{
hours = "0" + hours;
}
Related
It amazes me that JavaScript's Date object does not implement an add function of any kind.
I simply want a function that can do this:
var now = Date.now();
var fourHoursLater = now.addHours(4);
function Date.prototype.addHours(h) {
// How do I implement this?
}
I would simply like some pointers in a direction.
Do I need to do string parsing?
Can I use setTime?
How about milliseconds?
Like this:
new Date(milliseconds + 4*3600*1000 /* 4 hours in ms */)?
This seems really hackish though - and does it even work?
JavaScript itself has terrible Date/Time API's. Nonetheless, you can do this in pure JavaScript:
Date.prototype.addHours = function(h) {
this.setTime(this.getTime() + (h*60*60*1000));
return this;
}
Date.prototype.addHours= function(h){
this.setHours(this.getHours()+h);
return this;
}
Test:
alert(new Date().addHours(4));
The below code will add 4 hours to a date (example, today's date):
var today = new Date();
today.setHours(today.getHours() + 4);
It will not cause an error if you try to add 4 to 23 (see the documentation):
If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly
It is probably better to make the addHours method immutable by returning a copy of the Date object rather than mutating its parameter.
Date.prototype.addHours= function(h){
var copiedDate = new Date(this.getTime());
copiedDate.setHours(copiedDate.getHours()+h);
return copiedDate;
}
This way you can chain a bunch of method calls without worrying about state.
The version suggested by kennebec will fail when changing to or from DST, since it is the hour number that is set.
this.setUTCHours(this.getUTCHours()+h);
will add h hours to this independent of time system peculiarities.
Jason Harwig's method works as well.
Get a date exactly two hours from now, in one line.
You need to pass milliseconds to new Date.
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
or
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
let nowDate = new Date();
let expiryDate = new Date(new Date().setHours(new Date().getHours() + 2));
let expiryDate2 = new Date(Date.now() + 2 * (60 * 60 * 1000) );
console.log('now', nowDate);
console.log('expiry', expiryDate);
console.log('expiry 2', expiryDate2);
You can use the Moment.js library.
var moment = require('moment');
foo = new moment(something).add(10, 'm').toDate();
I also think the original object should not be modified. So to save future manpower here's a combined solution based on Jason Harwig's and Tahir Hasan answers:
Date.prototype.addHours= function(h){
var copiedDate = new Date();
copiedDate.setTime(this.getTime() + (h*60*60*1000));
return copiedDate;
}
If you would like to do it in a more functional way (immutability) I would return a new date object instead of modifying the existing and I wouldn't alter the prototype but create a standalone function. Here is the example:
//JS
function addHoursToDate(date, hours) {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
//TS
function addHoursToDate(date: Date, hours: number): Date {
return new Date(new Date(date).setHours(date.getHours() + hours));
}
let myDate = new Date();
console.log(myDate)
console.log(addHoursToDate(myDate,2))
There is an add in the Datejs library.
And here are the JavaScript date methods. kennebec wisely mentioned getHours() and setHours();
Check if it’s not already defined. Otherwise, define it in the Date prototype:
if (!Date.prototype.addHours) {
Date.prototype.addHours = function(h) {
this.setHours(this.getHours() + h);
return this;
};
}
This is an easy way to get an incremented or decremented data value.
const date = new Date()
const inc = 1000 * 60 * 60 // an hour
const dec = (1000 * 60 * 60) * -1 // an hour
const _date = new Date(date)
return new Date(_date.getTime() + inc)
return new Date(_date.getTime() + dec)
Another way to handle this is to convert the date to unixtime (epoch), then add the equivalent in (milli)seconds, then convert it back. This way you can handle day and month transitions, like adding 4 hours to 21, which should result in the next day, 01:00.
SPRBRN is correct. In order to account for the beginning/end of the month and year, you need to convert to Epoch and back.
Here's how you do that:
var milliseconds = 0; //amount of time from current date/time
var sec = 0; //(+): future
var min = 0; //(-): past
var hours = 2;
var days = 0;
var startDate = new Date(); //start date in local time (we'll use current time as an example)
var time = startDate.getTime(); //convert to milliseconds since epoch
//add time difference
var newTime = time + milliseconds + (1000*sec) + (1000*60*min) + (1000*60*60*hrs) + (1000*60*60*24*days);
var newDate = new Date(newTime); //convert back to date; in this example: 2 hours from right now
Or do it in one line (where variable names are the same as above:
var newDate =
new Date(startDate.getTime() + millisecond +
1000 * (sec + 60 * (min + 60 * (hours + 24 * days))));
For a simple add/subtract hour/minute function in JavaScript, try this:
function getTime (addHour, addMin){
addHour = (addHour ? addHour : 0);
addMin = (addMin ? addMin : 0);
var time = new Date(new Date().getTime());
var AM = true;
var ndble = 0;
var hours, newHour, overHour, newMin, overMin;
// Change form 24 to 12 hour clock
if(time.getHours() >= 13){
hours = time.getHours() - 12;
AM = (hours>=12 ? true : false);
}else{
hours = time.getHours();
AM = (hours>=12 ? false : true);
}
// Get the current minutes
var minutes = time.getMinutes();
// Set minute
if((minutes + addMin) >= 60 || (minutes + addMin) < 0){
overMin = (minutes + addMin) % 60;
overHour = Math.floor((minutes + addMin - Math.abs(overMin))/60);
if(overMin < 0){
overMin = overMin + 60;
overHour = overHour-Math.floor(overMin/60);
}
newMin = String((overMin<10 ? '0' : '') + overMin);
addHour = addHour + overHour;
}else{
newMin = minutes + addMin;
newMin = String((newMin<10 ? '0' : '') + newMin);
}
// Set hour
if((hours + addHour >= 13) || (hours + addHour <= 0)){
overHour = (hours + addHour) % 12;
ndble = Math.floor(Math.abs((hours + addHour)/12));
if(overHour <= 0){
newHour = overHour + 12;
if(overHour == 0){
ndble++;
}
}else{
if(overHour == 0){
newHour = 12;
ndble++;
}else{
ndble++;
newHour = overHour;
}
}
newHour = (newHour<10 ? '0' : '') + String(newHour);
AM = ((ndble + 1) % 2 === 0) ? AM : !AM;
}else{
AM = (hours + addHour == 12 ? !AM : AM);
newHour = String((Number(hours) + addHour < 10 ? '0': '') + (hours + addHour));
}
var am = (AM) ? 'AM' : 'PM';
return new Array(newHour, newMin, am);
};
This can be used without parameters to get the current time:
getTime();
Or with parameters to get the time with the added minutes/hours:
getTime(1, 30); // Adds 1.5 hours to current time
getTime(2); // Adds 2 hours to current time
getTime(0, 120); // Same as above
Even negative time works:
getTime(-1, -30); // Subtracts 1.5 hours from current time
This function returns an array of:
array([Hour], [Minute], [Meridian])
If you need it as a string, for example:
var defaultTime: new Date().getHours() + 1 + ":" + new Date().getMinutes();
I think this should do the trick
var nextHour = Date.now() + 1000 * 60 * 60;
console.log(nextHour)
You can even format the date in desired format using the moment function after adding 2 hours.
var time = moment(new Date(new Date().setHours(new Date().getHours() + 2))).format("YYYY-MM-DD");
console.log(time);
A little messy, but it works!
Given a date format like this: 2019-04-03T15:58
//Get the start date.
var start = $("#start_date").val();
//Split the date and time.
var startarray = start.split("T");
var date = startarray[0];
var time = startarray[1];
//Split the hours and minutes.
var timearray = time.split(":");
var hour = timearray[0];
var minute = timearray[1];
//Add an hour to the hour.
hour++;
//$("#end_date").val = start;
$("#end_date").val(""+date+"T"+hour+":"+minute+"");
Your output would be: 2019-04-03T16:58
The easiest way to do it is:
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
It will add 2 hours to the current time.
The value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time).
The value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time).
I wanna format the output after getting the values of Date.getHours(), Date.getMinutes() and Date.getSeconds().
Here is the long way:
var dt = new Date();
var HH = dt.getHours();
var mm = dt.getMinutes();
var ss = dt.getSeconds();
HH = HH < 10 ? '0' + HH : HH;
mm = mm < 10 ? '0' + mm : mm;
ss = ss < 10 ? '0' + ss : ss;
My question: How can I compress the last part to .toString('D2') function?
What I wanna archive:
var dt = new Date();
var HH = dt.getHours().toString('D2');
var mm = dt.getMinutes().toString('D2');
var ss = dt.getSeconds().toString('D2');
p/s: .toString('D2') is same meaning with Standard Numeric Format Strings. Like C# syntax:
int i = 1;
Console.WriteLine(i.ToString("D2")); // output: 01
I don't think Javascript has that kind of support. You would need to either write an ancillary function or install a library.
The closest I can think of for a one-liner is
("0"+dt.getSeconds()).slice(-2)
after this answer.
Something like the following should work:
var HH = ('0'+dt.getHours().toString()).slice(-2);
Similar approach for the others.
You can also avoid explicitly calling toString, thus:
var HH = ('0'+dt.getHours()).slice(-2);
var dt = new Date();
var today = dt.toJSON().slice(0, 10);
var time = dt.toJSON().slice(11, -1);
This function should be able to provide the solution to your problem. While this is not exactly the way you would like to do it, it is the easiest.
function decimalFormat(precision, number) {
if (arguments.length !== 2)
throw new Error("Invalid number of arguments!");
else if (typeof precision !== "number" || typeof number !== "number")
throw new TypeError("Invalid parameter type!");
var zeros = "0";
for (var i = 0; i < Math.abs(precision); i++)
zeros += "0";
return (zeros + number.toString()).slice(-1 * (Math.abs(precision)));
}
alert(decimalFormat(10, 21));
alert(decimalFormat(2, 5221));
alert(decimalFormat(4, 221));
I want to subtract the two different 24 hours time format.
I had tried with following :
var startingTimeValue = 04:40;
var endTimeValue = 00:55;
var hour = startingTimeValue.split(":");
var hour1 = endTimeValue.split(":");
var th = 1 * hour[0] - 1 * hour1[0];
var tm = 1 * hour[1] - 1 * hour1[1];
var time = th+":"+tm;
This code is working fine if second minutes is not greater than the first.but other case it will return minus values.
The above code sample values result :
time1 : 04:40
time2 : 00:55
The result should be : 03:45 (h:mi) format.
But right now I am getting 04:-5 with minus value.
I had tried with the link as : subtract minutes from calculated time javascript but this is not working with 00:00 format.
So how to calculate the result value and convert into hours and minutes?
I would try something like the following.
The way I see it, it is always better to break it down to a common unit and then do simple math.
function diffHours (h1, h2) {
/* Converts "hh:mm" format to a total in minutes */
function toMinutes (hh) {
hh = hh.split(':');
return (parseInt(hh[0], 10) * 60) + parseInt(hh[1], 10);
}
/* Converts total in minutes to "hh:mm" format */
function toText (m) {
var minutes = m % 60;
var hours = Math.floor(m / 60);
minutes = (minutes < 10 ? '0' : '') + minutes;
hours = (hours < 10 ? '0' : '') + hours;
return hours + ':' + minutes;
}
h1 = toMinutes(h1);
h2 = toMinutes(h2);
var diff = h2 - h1;
return toText(diff);
}
Try:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
var subtractedValue = time1 - time2;
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
DEMO
This solution utilizes javascript built-in date. How it works:
var time1 = Date.UTC(0,0,0,4,40,0);
var time2 = Date.UTC(0,0,0,0,55,0);
time1, time2 is the number of miliseconds since 01/01/1970 00:00:00 UTC.
var subtractedValue = time1 - time2;
subtractedValue is the difference in miliseconds.
var timeResult = new Date(subtractedValue);
console.log(timeResult.getUTCHours() + ":" + timeResult.getUTCMinutes());
These lines reconstruct a date object to get hours and minutes.
This works better , A fiddle I just found
var difference = Math.abs(toSeconds(a) - toSeconds(b));
fiddle
This method may work for you:
function timeDiff(s,e){
var startTime = new Date("1/1/1900 " + s);
var endTime = new Date("1/1/1900 " + e);
var diff = startTime - endTime;
var result = new Date(diff);
var h = result.getUTCHours();
var m = result.getUTCMinutes();
return (h<=9 ? '0' + h : h) + ':' + (m <= 9 ? '0' + m : m);
}
var startingTimeValue = "04:40";
var endTimeValue = "00:55";
var formattedDifference = timeDiff(startingTimeValue,endTimeValue);
Demo: http://jsfiddle.net/zRVSg/
I'm basically trying to get the hours, minutes, and seconds of a date in javascript to read like this: '123456'. I am doing this with the following code:
var date;
date = new Date();
var time = date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
Only problem is when I add them together, I keep getting the sum, not a nice line of 6 numbers like I want.
Any Suggestions?
var time = '' + date.getUTCHours() + date.getUTCMinutes() + date.getUTCSeconds();
edit:
To account for zero-padding you can do something like:
function format(x){
if (x < 10) return '0' + x;
return x;
}
var date;
date = new Date();
var time = '' + format(date.getUTCHours()) + format(date.getUTCMinutes()) + format(date.getUTCSeconds());
Convert the numerical value to a string:
var date;
date = new Date();
var time = date.getUTCHours().toString() + date.getUTCMinutes().toString() + date.getUTCSeconds().toString();
If you want it to always be 6 characters long, you need to pad the values if they are < 10. For example:
var hours = date.getUTCHours();
if (hours < 10)
hours = '0' + hours.toString();
else hours = hours.toString();
var mins = date.getUTCMinutes();
if (mins < 10)
mins = '0' + mins.toString();
else mins = mins.toString();
var secs = date.getUTCSeconds();
if (secs < 10)
secs = '0' + secs.toString();
else secs = secs.toString();
var time = hours + mins + secs;
That's happening because those functions return an Integer type. If you want to add the digits themself togheter, try converting every variable to string using toString()
$.now() gives me the time as miliseconds. I need to show it something like hh:mm:ss
How can I do that in Jquery?
I'd suggest just using the Javascript Date object for this purpose.
var d = new Date();
var time = d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
Edit: I just came across the method below, which covers formatting issues such as the one mike-samuel mentioned and is cleaner:
var time = d.toLocaleTimeString();
function formatTimeOfDay(millisSinceEpoch) {
var secondsSinceEpoch = (millisSinceEpoch / 1000) | 0;
var secondsInDay = ((secondsSinceEpoch % 86400) + 86400) % 86400;
var seconds = secondsInDay % 60;
var minutes = ((secondsInDay / 60) | 0) % 60;
var hours = (secondsInDay / 3600) | 0;
return hours + (minutes < 10 ? ":0" : ":")
+ minutes + (seconds < 10 ? ":0" : ":")
+ seconds;
}
JSFiddle example here
http://jsfiddle.net/NHhMv/
The jquery now is nothing but
The $.now() method is a shorthand for the number returned by the expression
(new Date).getTime().
from jquery
http://api.jquery.com/jQuery.now/
and follow this link
Where can I find documentation on formatting a date in JavaScript?
new Date().toString().split(' ')[4]
or
new Date().toString().match(/\d{2}:\d{2}:\d{2}/)[0]
The toString method is basically an alias for toLocaleString in most implementations. This will return the time in the user's timezone as opposed to assuming UTC by using milliseconds if you use getTime (if you use getMilliseconds you should be OK) or toUTCString.
I'd suggest date-format jQuery plugin. Like this one or this one (I am using the former)
I'm way late to this, but thought i'd just throw this little snippet out there for the masses. This is something I use just to get a quick localized timestamp. It's pretty clean and handy.
function getStamp() {
var d = new Date();
var mm = d.getMilliseconds(), hh = d.getHours(),
MM = d.getMinutes(), ss = d.getSeconds();
return (hh < 10 ? "0" : "") + hh + (MM < 10 ? ":0" : ":") + MM + (ss < 10 ? ":0" : ":") + ss + ":" + mm;
};
jQuery doesn't have date formatting. You can roll your own with the JavaScript Date object, or you can use a library that does it for you. DateJS is one such library, which provides a rich set of formatting, parsing, and manipulation functionality. However, it hasn't been maintained in years. momentjs is under active development.