The following code is used to get a date value and then add two hours to it. I would really like to know how to give a condition to add that two hours only between 08:30 in the morning until 18:30 of the evening and skip both the days ( Saturday,Sunday ).
For example: if the given date was in 17:30 of Tuesday so it followed the rule it will be ( 17:30 (of Tuesday ) + 2 = 09:30 ( of Wednesday-the next day) and if the given date was in 17:00 (of Friday) it will be if we skip the week-ends 09:00 ( of Monday-skip week-ends ) etc...
var now = new Date(Date.parse($(".x-form-hidden.x-form-field :eq(0)").val()));
now.setHours(now.getHours() + 2);
var dayVar = "";
if (now.getDate() < 10) {
dayVar = 0 + "" + now.getDate()
} else {
dayVar = now.getDate();
}
var dateString =
now.getFullYear() + "-" +
(now.getMonth() + 1) + "-" +
dayVar + " " +
now.getHours() + ":" + now.getMinutes() + ":0" + now.getSeconds();
$(".x-form-hidden.x-form-field :eq(1)").attr('value', dateString);
function addTwoHours(date) {
//date to decimal
var day = date.getDay() - 1;
var hour = date.getHours() - 8;
var decimal = day * 10 + hour;
//add two hours
decimal += 2;
//decimal to date
var newDay = Math.floor(decimal / 10);
var nextDay = newDay - day == 1;
var weekEnd = newDay % 5 == 0;
var newHour = (decimal % 10) + 8;
var newDate = new Date(date.getTime() + (nextDay?24:0) * (weekEnd?3:1) * 60 * 60 * 1000);
newDate.setHours(newHour);
return newDate;
}
Your time range represent 10 hours per day for 5 days a week, so it's easy to map to a continuous block of 50 hours. Considering then the units and tens gives the shift.
The following example gets the date for Friday 1 Feb. 17:15, which returns Monday 4 Feb 9:15. addTwoHours(new Date(2013, 1, 1, 17, 15));
Related
I try to code with JavaScript and now, I have another problem. The intended goal is to calculate the number of days and to return list of those date between two selected dates from datepicker. The trick is: the system should provide two option: during all day of the week (including Saturday and Sunday) and only during working days. I tried to do this on my own, but I am stuck. I have also tried to find out if anyone happened to asked the same question, but the result is no. Here is my code. Can anyone help me with this? Thank you!
$("#calculate").click(function() {
// TO CALCULATE TOTAL DAYS
startdate.setHours(0, 0, 0, 1);
enddate.setHours(23, 59, 59, 999);
var days = Math.ceil(enddate - startdate) / (1000 * 60 * 60 * 24);
var weeks = Math.floor(days / 7);
days = days - (weeks * 2);
var month = startdate.getMonth();
var day = startdate.getDate();
var year = startdate.getFullYear();
// ONLY DURING WORKING DAYS
$("#weekday").change(function() {
if ($(this).is(':checked')) {
var startday = startdate.getDay();
var endday = enddate.getDay();
if (startday - endday > 1) {
days = days - 2
}
if (startday == 0 && endday != 6) {
days = days - 1
}
if (endday == 6 && startday != 0) {
days = days - 1
}
// TO SHOW THE LIST OF DATE BETWEEN START AND END DATE
while (startdate <= enddate) {
if (startday < 6 && startday > 0) {
month = startdate.getMonth() + 1
}
if (month <= 9) {
month = "0" + month
}
var day = startdate.getdate();
if (day <= 9) {
day = "0" + day
}
}
startdate.setDate(startdate.getDate() + 1);
}
})
})
var quantity = $("#quantity").val();
var delivery = Math.round(quantity / days);
var datearray = document.write(day + "." + month + "." + startdate.getFullYear());
if (enddate < startdate) {
alert("Start date must be earlier than end date!")
} else if (quantity == 0) {
alert("Quantity must be bigger than 0")
} else {
append("<br>Total " + days + " selected days<br/>");
append("<br>Shipment" + delivery + " pc(s) per day<br/>");
append("<br>During period of" + datearray + "<br/>")
}
});
I'd like to calculate the elapsed time between two dates. I saw some examples on the internet (most of them on this site), but found nothing useful. I'd like to write a function can call like this:
calculateDifference('2012-02-01 15:31')
There is no second parameter, since it is the current date. I have a code I'm currently using, which is:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (date_diff.getHours() > 0) {
respvalue += (date_diff.getHours() - 1) + " hour(s) and ";
}
respvalue += date_diff.getMinutes() + " minute(s) ago.";
return respvalue;
}
And the result is and should be:
1 day(s), 14 hour(s) and 17 minute(s)
For some reasons there are differences (when 1 day passed it shows 0 etc) and it works only with chrome, in IE and FF it returns with the date I passed as the parameter.
Once again: I'd like to calculate the difference between the current date and a given date in the next format:
1 day(s), 14 hour(s) and 17 minute(s)
I don't care about the months, years. Only hours, mins and secs. Thank you in advance!
Try this:
function get_time_diff(_datetime )
{
var datetime = new Date( _datetime ).getTime();
var now = new Date().getTime();
if( isNaN(datetime) )
{
return " on " + _datetime;
}
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var hours = Math.floor(milisec_diff / (1000 * 60 * 60) - days * 24);
var minutes = Math.floor(milisec_diff / (1000 * 60) - days * 24 * 60 - hours * (60));
var respvalue ='';
if (days > 0) {
respvalue += days + " day(s), ";
}
if (hours > 0) {
respvalue += hours + " hour(s) and ";
}
respvalue += minutes + " minute(s) ago.";
return respvalue;
}
The problem is that your date format is not valid, so Firefox can't parse your strings as dates.
You can use
function get_time_diff(datetime) {
var milisec_diff = Math.abs(new Date() - new Date(datetime)),
diff = new Date(milisec_diff),
days = milisec_diff / 3600e3 / 24 | 0,
hours = diff.getUTCHours(),
respvalue = '';
if (days)
respvalue += days + " day(s), ";
if (hours)
respvalue += hours + " hour(s) and ";
respvalue += diff.getUTCMinutes() + " minute(s) ago.";
return respvalue;
}
get_time_diff('2012-02-01T15:31Z');
Where the date 2012-02-01T15:31Z is in ISO8601, and the Z means UTC time (note some browsers may not support it).
This seems simplest to me:
http://jsbin.com/tusul/9/edit
// end date is optional, it will assume the current date if not supplied.
// if timezone is not supplied, it will assume local browser time.
function calculateDateDiff(beginDate, endDate) {
var currentDate;
if (typeof(endDate) == 'undefined') {
currentDate = new Date();
} else {
currentDate = new Date(endDate);
}
var targetDate = new Date(beginDate);
var differenceDate;
if (currentDate > targetDate) {
differenceDate = new Date(currentDate - targetDate);
} else {
differenceDate = new Date(targetDate - currentDate);
}
return('Days: ' + (differenceDate.getUTCDate() -1) + ', Hours: ' + differenceDate.getUTCHours() + ', Minutes: ' + differenceDate.getUTCMinutes() + ', Seconds: ' + differenceDate.getUTCSeconds());
}
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04'));
console.log(calculateDateDiff('05-22-2014 01:02:03', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04Z'));
console.log(calculateDateDiff('05-22-2014 01:02:03Z', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03-500', '05-22-2014 02:03:04-600'));
console.log(calculateDateDiff('05-22-2014 01:02:03+1000', '05-22-2014 02:03:04-600'));
I've been working on this script to get the difference between 2 dates. But the hours will mess up the script (http://jsfiddle.net/HuGvd/).
When the script enters a new month new the same day the script stops working correctly. I've also tried adding minutes to this script with no luck really need help with this one guys.
function getDateDiff(timestamp) {
if (null === timestamp || timestamp === "" || timestamp === "undefined") return "?";
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var d1 = new Date();
var d1Y = d1.getFullYear();
var d2Y = parseInt(splitDate[0], 10);
var d1M = d1.getMonth() + 1;
var d2M = parseInt(splitDate[1], 10);
var d1D = d1.getDate();
var d2D = parseInt(splitDate[2], 10);
var d1H = d1.getHours();
var d2H = parseInt(splitTime[0], 10);
var diffInHours = (d1H + 24 * d1D + 30) - (d2H + 24 * d2D + 30);
if (diffInHours < 24) return diffInHours + " hour";
var diffInDays = (d1D + 30 * d1M + 12) - (d2D + 30 * d2M + 12);
if (diffInDays < 7) return diffInDays + " days";
else if (diffInDays >= 7 && diffInDays < 14) return "1 week";
else if (diffInDays >= 14 && diffInDays < 30) return Math.floor(diffInDays / 7) + " weeks";
var diffInMonths = (d1M + 12 * d1Y) - (d2M + 12 * d2Y);
if (diffInMonths <= 1) return "1 month";
else if (diffInMonths < 12) return diffInMonths + " months";
var diffInYears = Math.floor(diffInMonths / 12);
if (diffInYears <= 1) return "1 year";
else if (diffInYears < 12) return diffInYears + " years";
}
Date/time functionality is extremely complex with more edge cases than you can possibly cover... don't roll your own solution, use built-in functionality. You can find the number of milliseconds between two dates in javascript like this:
var now = new Date();
var then = new Date(timestamp);
var diffMS = now - then;
From there, it's not too difficult to convert to whatever unit your want based on how you want to display it.
http://jsfiddle.net/AMDXq/
As a side note, this is a fairly common problem. I haven't looked, but I'm sure there's a plugin or library out there for this.
Here is a solution for finding the difference between two dates. The strategy is to convert strings to date objects, then calculate the difference and return an array of values for years, months, days, etc.
I've added a parameter for "precise" so that by default it returns a value in whole days (e.g. 2013-08-13T23:59:59Z to 2013-08-14T00:00:01Z is one day) or precise (where the above difference is 2 seconds).
// Expects start date to be before end date
// Default is to deal in whole days. For precise differences
// (hours, minutes and seconds), set precise to true
function dateDifference(start, end, precise) {
var timeDiff, years, months, days, hours, minutes, seconds;
// Copy date objects so don't modify originals
var s = new Date(+start);
var e = new Date(+end);
console.log(s, e);
// If not precise, set h,m,s to zero
if (!precise) {
s.setUTCHours(0,0,0,0);
e.setUTCHours(0,0,0,0);
console.log(s, e);
}
// Get estimate of year difference
years = e.getUTCFullYear() - s.getUTCFullYear();
// Add difference to start, if greater than end, remove one year
// Note start from restored start date as adding and subtracting years
// may not be symetric
s.setFullYear(s.getUTCFullYear() + years);
if (s > e) {
--years;
s = new Date(+start);
s.setFullYear(s.getUTCFullYear() + years);
}
// Get estimate of months
months = e.getUTCMonth() - s.getUTCMonth();
months += months < 0? 12 : 0;
// Add difference to start, adjust if greater
s.setUTCMonth(s.getUTCMonth() + months);
if (s > e) {
--months;
s = new Date(+start);
s.setUTCFullYear(s.getUTCFullYear() + years);
s.setUTCMonth(s.getUTCMonth() + months);
}
// Get remaining time difference
timeDiff = e - s;
days = timeDiff / 8.64e7 | 0;
hours = (timeDiff % 8.64e7) / 3.6e6 | 0;
minutes = (timeDiff % 3.6e6) / 6e4 | 0;
seconds = ((timeDiff % 6e4) / 1e3).toFixed(3);
console.log(years, months, days, hours, minutes, seconds);
return [years, months, days, hours, minutes, seconds];
}
// Simple caluculation of days between two ES5 date objects
function daysDifference(start,end) {
return ((end - start) / 8.64e7).toFixed(2);
}
// Expects input in ISO8601 format: yyyy-mm-ddThh:mm:ss.sssZ
function dateFromString(s) {
s = s.split(/\D/);
s[6] = s[6]? ('0.'+ s[6]) * 1000 : 0;
return new Date(Date.UTC(s[0],--s[1],s[2],s[3],s[4],s[5],s[6]));
}
function getDateDiff(start, end, precise) {
var d = dateDifference(dateFromString(start), dateFromString(end), precise);
return d[0] + ' years, ' + d[1] + ' months, ' + d[2] + ' days' +
(precise? ', ' + d[3] + ' hours, ' + d[4] + ' minutes and ' + d[5] + ' seconds' : '') ;
}
function getDaysDiff(start, end) {
var d = daysDifference(dateFromString(start), dateFromString(end));
return d + ' days';
}
</script>
<!-- Some HTML to show how to use it -->
<form onsubmit="this.doCalc.onclick(); return false;">
<label for="startDate">Start date (yyyy-mm-dd)<input name="startDate" id="startDate"
value="2012-08-09T22:15:03.22" size="25"></label>
<br>
<label for="endDate">End date (yyyy-mm-dd)<input name="endDate" id="endDate"
value="2013-08-13T12:10:03.22" size="25"></label>
<br>
<label for="dateDifference">Date difference: <input name="dateDifference" readonly size="100"></label>
<br>
<label for="daysDifference">Days difference: <input name="daysDifference" readonly size="100"></label>
<br>
<label for="precise"><input type="checkbox" value="precise" name="precise" id="precise">Precise?</label>
<br>
<input type="button" value="Calculateā¦" name="doCalc" onclick="
this.form.dateDifference.value = getDateDiff(this.form.startDate.value, this.form.endDate.value,
this.form.precise.checked);
this.form.daysDifference.value = getDaysDiff(this.form.startDate.value, this.form.endDate.value);
">
<input type="reset">
</form>
What's wrong with this script?
When I set my clock to say 29/04/2011 it adds 36/4/2011 in the week input! but the correct date should be 6/5/2011
var d = new Date();
var curr_date = d.getDate();
var tomo_date = d.getDate()+1;
var seven_date = d.getDate()+7;
var curr_month = d.getMonth();
curr_month++;
var curr_year = d.getFullYear();
var tomorrowsDate =(tomo_date + "/" + curr_month + "/" + curr_year);
var weekDate =(seven_date + "/" + curr_month + "/" + curr_year);
{
jQuery("input[id*='tomorrow']").val(tomorrowsDate);
jQuery("input[id*='week']").val(weekDate);
}
var date = new Date();
date.setDate(date.getDate() + 7);
console.log(date);
And yes, this also works if date.getDate() + 7 is greater than the last day of the month. See MDN for more information.
Without declaration
To return timestamp
new Date().setDate(new Date().getDate() + 7)
To return date
new Date(new Date().setDate(new Date().getDate() + 7))
Something like this?
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
alert(res);
convert to date again:
date = new Date(res);
alert(date)
or alternatively:
date = new Date(res);
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = date.getMinutes();
// seconds part from the timestamp
var seconds = date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = date + '-' + hours + ':' + minutes + ':' + seconds;
alert(formattedTime)
In One line:
new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
The simple way to get a date x days in the future is to increment the date:
function addDays(dateObj, numDays) {
return dateObj.setDate(dateObj.getDate() + numDays);
}
Note that this modifies the supplied date object, e.g.
function addDays(dateObj, numDays) {
dateObj.setDate(dateObj.getDate() + numDays);
return dateObj;
}
var now = new Date();
var tomorrow = addDays(new Date(), 1);
var nextWeek = addDays(new Date(), 7);
alert(
'Today: ' + now +
'\nTomorrow: ' + tomorrow +
'\nNext week: ' + nextWeek
);
Using the Date object's methods will could come in handy.
e.g.:
myDate = new Date();
plusSeven = new Date(myDate.setDate(myDate.getDate() + 7));
var days = 7;
var date = new Date();
var res = date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var d = new Date(res);
var month = d.getMonth() + 1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month < 10 ? '0' : '') + month + '/' +
(day < 10 ? '0' : '') + day;
$('#txtEndDate').val(output);
var future = new Date(); // get today date
future.setDate(future.getDate() + 7); // add 7 days
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();
console.log(finalDate);
You can add or increase the day of week for the following example and hope this will helpful for you.Lets see....
//Current date
var currentDate = new Date();
//to set Bangladeshi date need to add hour 6
currentDate.setUTCHours(6);
//here 2 is day increament for the date and you can use -2 for decreament day
currentDate.setDate(currentDate.getDate() +parseInt(2));
//formatting date by mm/dd/yyyy
var dateInmmddyyyy = currentDate.getMonth() + 1 + '/' + currentDate.getDate() + '/' + currentDate.getFullYear();
Two problems here:
seven_date is a number, not a date. 29 + 7 = 36
getMonth returns a zero based index of the month. So adding one just gets you the current month number.
I have the time stored as a fraction (done so it can be displayed on a graph), e.g. 15.5 is 3.30pm and 23.25 is 11.15pm. I need to turn those numbers into strings in the format HH:MM:SS. Is there a simple way of doing this?
var fraction = 23.5;
var date = new Date(2000, 1, 1); // use any date as base reference
date.setUTCSeconds(fraction * 3600); // add number of seconds in fractional hours
Then use a date formatting script such as this, or Date.js if you're not fond or formatting and padding.
date.format("HH:MM:ss"); // 23:30:00
See an example. I'm using the formatting function from here.
Something like this ?
var fraction = 14.5;
var hours = Math.floor(fraction); // extract the hours (in 24 hour format)
var mins = 60 * (fraction - hours); // calculate the minutes
t = new Date(); // create a date/time object
t.setHours(hours); // set the hours
t.setMinutes(mins); // set the mins
console.log(t.toTimeString()); //show it
or completely manual
var fraction = 14.5;
var hours = Math.floor(fraction);
var mins = 60 * (fraction - hours);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + mins).substr(-2) + ':00 ' + ampm;
console.log(formatted);
Update
And a version with seconds as well..
var fraction = 14.33;
var hours = Math.floor(fraction);
var allseconds = 3600 * (fraction - hours);
var minutes = Math.floor(allseconds / 60);
var seconds = Math.floor(allseconds % 60);
var ampm = ((fraction % 24) < 12) ? 'am' : 'pm';
formatted = ('0' + hours % 12).substr(-2) + ':' + ('0' + minutes).substr(-2) + ':' + ('0' + seconds).substr(-2) + ' ' + ampm;
console.log(formatted);
Manual function:
var time = function(num) {
if(num < 0 || num >= 24) {throw "Invalid number");}
var x = num > 13 ? num - 12 : num;
var h = Math.floor(x);
var min = x - h;
var ampm = num >= 12 && num < 24 ? "pm" : "am";
return (h + ":" + Math.floor(min * 60) + ampm);
};
Tests:
time(13.40); // 1:24pm
time(11.25); // 11:15pm
time(12.50); // 12:30pm
time(23.50); // 11:30pm
time(0.50); // 0:30am
time(24.00); // error!!