I want to add 30 minutes and then one hour to my variable which i already have my own date
var initialDate = '10:00';
So
if (some condition){
// i add 30 minutes ->10:30
}elseif(another condition){
// i add 1hour ->11:00
}
I tried this but doesn't work
var initialDate = '10:00';
var theAdd = new Date(initialDate);
var finalDate = theAdd.setMinutes(theAdd.getMinutes() + 30);
If I understand you correctly, the following will help you.
You need to add momentjs dependency via script tag and you can Parse, validate, manipulate, and display dates in JavaScript.
You can find more documentation regarding this in momentjs website
console.log(moment.utc('10:00','hh:mm').add(1,'hour').format('hh:mm'));
console.log(moment.utc('10:00','hh:mm').add(30,'minutes').format('hh:mm'));
<script src="https://momentjs.com/downloads/moment-with-locales.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
var theAdd = new Date();
// Set Hours, minutes, secons and miliseconds
theAdd.setHours(10, 00, 00, 000);
if (some condition) {
// add 30 minutes --> 10:30
theAdd.setMinutes(theAdd.getMinutes() + 30);
}
elseif (some condition) {
// add 1 hour --> 11:00
theAdd.setHours(theAdd.getHours() + 1);
}
Then you print the var theAdd to obtain the date and time.
To obtain just the time:
theAdd.getHours() + ":" + theAdd.getMinutes();
This should do the job. Dates need a year and month in their constructor, and you have to specify larger units of time if you specify and smaller ones, so it needs a day as well. Also, you have to pass in the hours and minutes separately. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date.
var initialDate = '10:00';
var theAdd = new Date(1900,0,1,initialDate.split(":")[0],initialDate.split(":")[1]);
if(30 min condition){
theAdd.setMinutes(theAdd.getMinutes() + 30);
} else if (1 hour condition){
theAdd.setHours(theAdd.getHours() + 1);
}
console.log(theAdd.getHours()+":"+theAdd.getMinutes());
Here is a javascript function that will add minutes to hh:mm time string.
function addMinutes(timeString, addMinutes) {
if (!timeString.match(/^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/))
return null;
var timeSplit = timeString.split(':');
var hours = parseInt(timeSplit[0]);
var minutes = parseInt(timeSplit[1]) + parseInt(addMinutes);
hours += Math.floor(minutes / 60);
while (hours >= 24) {
hours -= 24;
}
minutes = minutes % 60;
return ('0' + hours).slice(-2) + ':' + ('0' +minutes).slice(-2);
}
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).
anyone can help me? Example, I want a countdown timer but inverted, example:
I insert my date and hour in javascript or mysqL (doesn't matter) and it will count ..
Example: I inserted: 01/07/2015
today the counter will show: 1day 1hour 19min
If you don't want to use jquery then you can do something like this:
var startTime = +new Date("07/01/2015"); // m/d/Y gets timestamp in ms
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var day = hour * 24;
var element = document.getElementById('timer'); // target element for the timer
function countUp() {
// time between now and the start date
var time = Date.now() - startTime;
// days passed since start
var days = Math.floor(time / day);
time -= days * day;
// hours passed
var hours = Math.floor(time / hour);
time -= hours * hour;
// minutes passed
var minutes = Math.floor(time / minute);
// update element
element.innerHTML = days + 'day ' + hours + 'hour ' + minutes + 'min';
setTimeout(countUp, minute);
};
countUp();
<span id="timer"></span>
Since you want to use the jQuery Countdown plugin, you can just use it's built-in count up functionality. Take a look at the 'Count Up' tab of the jQuery Countdown page: http://keith-wood.name/countdown.html.
EDIT: Adding code example
$("#countdown").countdown({since: new Date(2015, 7-1, 1)});
#countdown {
float: left;
width: 240px;
}
<link href="http://keith-wood.name/css/jquery.countdown.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://keith-wood.name/js/jquery.plugin.js"></script>
<script src="http://keith-wood.name/js/jquery.countdown.js"></script>
<span id="countdown">
I'm trying to create a countdown.
Basically I have the time a client has placed an order (which is in dateTime format stored in db for eg. "2014-08-14 12:52:09") and I also have the time it takes to complete the order ( which is either in hours and minutes "1" 45", or just minutes "45").
I got a countdown script from the web and I'm having a bad time figuring out how to format both times so that the script understands.
I got this coming from db
Order time----> 12:52:09
expiry time ---> 45minutes
expiry time may sometimes including hours as well:
eg: expiry time ---> 1hour 45minutes.
the script I got from the web I enclosed inside a function at the moment:
JS:
function clockTicking(){
// set the date we're counting down to
var target_date = new Date("Aug 15, 2019").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
$('.countdown').html(days + "d, " + hours + "h, "+ minutes + "m, " + seconds + "s");
}, 1000);
}
Any help will be greatly appreciated.
You can change the beginning of the script to this
function setTimer(hours, minutes, dateTime){
var date = new Date(dateTime);
date.setHours(date.getHours() + hours);
date.setMinutes(date.getMinutes() + minutes);
var target_date = date.getTime();
// rest of script
}
then just call it with setTimer(1,30, "2014 09 24 00:23") to set the count down relative to 2014-09-24 01:53
Check it out here: jsFiddle
I would like to recommend Moment.js for this (and just about any kind of date/time parsing). While writing your own function might seem tempting, there are often many things that need to be taken into account and it's simply not worth it.
Using Moment.js, what you're trying to achieve can be done like this:
function clockTicking(){
var target_date = moment('Aug 15, 2019', 'MMM DD, YYYY');
// update the tag with id "countdown" every 1 second
setInterval(function () {
var moment_diff = moment.duration(target_date.diff(moment()));
// format countdown string + set tag value
$('.countdown').html(moment_diff.days() + "d, " + moment_diff.hours() + "h, "+ moment_diff.minutes() + "m, " + moment_diff.seconds() + "s");
}, 1000);
}
Of course, keep in mind that this particular example is not correct because the difference is too large (it will only work if the difference is less than a month), but it shouldn't be a problem since you mentioned in your original post that the difference should usually be measured in hours, not years.
I'd really consider using:
http://momentjs.com/docs/
If you're doing a fair amount of date time handling.
However, it looks like you're having trouble converting your two time formats to the date time object?
var stripNonNumberics = function(string) {
return Number(string.replace(/\D/g, ''));
}
var target_date = "1hour 45minutes"; // or var target_date = "45minutes";
var split_date = target_date.split(' ');
var minutes;
// If it has hours
if (split_date[1]) {
minutes = stripNonNumberics(split_date[1]) + (stripNonNumberics(split_date[0]) * 60);
} else {
minutes = stripNonNumberics(split_date[0]);
}
console.log(new Date(new Date().getTime() + minutes*60000););
I'm creating a site for my neighbor who has a Christmas light show.
The show runs every year from 6 December till 1 January twice an evening: at 6.30pm and at 8.00pm.
We want to add a countdown on the website which says:
next show: 00:00:00 (hh:mm:ss)
But how do I do that. When I search for it on the web every one says that I have to use an API for a countdown.
But they just use one date to count down to, so I think I have to write one myself in JavaScript.
Can anyone help with that?
I guess I have to use many if/else statements, starting with "is the month 1, 12 or something else?", followed by "has it yet been 18.30?" (I want 24-hours) and "has it already been 20.00" and so on.
But is there a better way, because this seems a lot of work to me.
JavaScript has a built-in date object that makes dealing with dates and times a bit less manual:
MDN documentation for JavaScript's date object
If you supply no arguments to its constructor, it'll give you the current date (according to the end user's computer):
var now = new Date();
You can set it to a specific date by supplying the year, month (zero-indexed from January), day, and optionally hour, minute and second:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
You can use greater- and less-than comparisons on these date objects to check whether a date is after or before another:
var now = new Date();
var first_show = new Date(now.getFullYear(), 11, 6, 18, 30);
alert(now < first_show);// Alerts true (at date of writing)
So, you could:
Create date objects for the current date, and each show this year (and for the 1st Jan shows next year)
Loop through the show dates in chronological order, and
Use the first one that's greater than the current date as the basis for your countdown.
Note: you should use something server-side to set now with accurate parameters, instead of just relying on new Date(), because if the end-user's computer is set to the wrong time, it'll give the wrong result.
Here's an example that will count down for 4 hours starting now() :
<script type="text/javascript">
var limit = new Date(), element, interval;
limit.setHours(limit.getHours() + 4);
window.onload = function() {
element = document.getElementById("countdown");
interval = setInterval(function() {
var now = new Date();
if (now.getTime() >= limit.getTime()) {
clearInterval(interval);
return;
}
var diff = limit.getTime() - now.getTime();
var hours = parseInt(diff / (60 * 60 * 1000));
diff = diff % (60 * 60 * 1000);
minutes = parseInt(diff / (60 * 1000));
diff = diff % (60 * 1000);
seconds = parseInt(diff / 1000);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
miliseconds = diff % 1000;
miliseconds = miliseconds.toString().substring(0, 2);
element.innerHTML = hours + ":" + minutes + ":" + seconds + ":" + miliseconds;
}, 10);
}
See it live here
I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);