Consider I have following date and time in 24 hours format.
Example
2015/04/02 12:00
2015/03/02 14:00
I have to subtract the above time with 9 hours so that I will get
2015/04/02 -> 3 (hours)
2015/03/02 -> 5 (hours)
HTML
<form name="formName" onsubmit="return checkDate(this)">
<input type="text" value="" name="date1" />
<input type="text" value="" name="date2"/>
<input type="submit" value="Submit">
</form>
<p id="demo"></p>
Javascript
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
var dateStart = new Date();
var dateEnd = new Date();
dateStart.setHours(9);
Start_sec = (date1/ 1000.0) - (dateStart/ 1000.0);
Start_hours = parseInt(Start_sec / 60 / 60);
document.getElementById("demo").innerHTML = Start_hours ;
return false;
}
Try the following code.
function checkDate(theForm)
{
var a = theForm.date1.value;
var b = theForm.date2.value;
var date1 = new Date(a);
var date2 = new Date(b);
date1.setHours(date1.getHours() - 9);
date2.setHours(date2.getHours() - 9);
document.getElementById("demo").innerHTML = "Date 1 : " + date1.toString() + "<br/>Date 2 : " + date2.toString();
return false;
}
If it is acceptable to use third party libraries, then you can achieve this task simply using moment.js. In one line, you can accomplish the task with this code:
moment('2015/04/02 12:00').subtract('hours',9).format('YYYY/MM/DD hh:mm')
//just a number plus the word 'hours'
.format('h [hours]')
//time only
.format('h:mm')
Occasionally I update this fiddle I maintain with more examples: http://jsfiddle.net/JamesWClark/9PAFg/
var date = new Date("2015/04/02 12:00");
var out = new Date(date.getTime() - 32400000); //9*60*60*1000
You can just literally subtract 9 hours directly...:
var t = new Date(2015,2,3,18);
t.setTime(t - 9*60*60*1000); //subtract 9 hours
Related
I'm looking for a way to fill a week form element according to the input of another week form element. I'm pretty new to Javascript.
Basically I need to get the difference of week between c1 and c2 form.
Then fill d1 and d2 automatically with the same difference of week but with d1 starting one week after c2.
Exemple:
c1 = "2018-W01"
c2 = "2018-W05"
Should set d1 and d2 values to:
d1 = "2018-W06"
d2 = "2018-W10"
<input type="week" id="c1">
<input type="week" id="c2">
<input type="week" id="d1" readonly>
<input type="week" id="d2" readonly>
<script>
function myFunction() {
var d1 = document.getElementById("c1").value;
var d2 = document.getElementById("c2").value;
var year = d1.substring(0,4); //2018
var day1 = d1.substring(6,); //01
var day2 = d2.substring(6,); //05
var difference = day2 - day1; //5
document.getElementById("d1").value = d1 + difference; // ?
document.getElementById("d2").value = d2 + difference;
</script>
This piece of code obviously doesn't work but shows what I think.
This does rise a problem with dates that overlap between two years.
Thanks for the help!
try this..
function myFunction(d1, d2) {
var year1 = parseInt(d1.substring(0, 4)); //2018
var year2 = parseInt(d2.substring(0, 4));
var yearDiff = Math.abs(year1 - year2);
var weeksInYears = 52 * yearDiff;
var day1 = parseInt(d1.substring(6, )); //01
var day2 = parseInt(d2.substring(6, )); //05
var difference = Math.abs(weeksInYears - (day2 - day1)); // handled dates with different years
var week1 = day2 + 1;
var week2 = week1 + difference;
week1 = ((week1 < 10 ? '0' : '') + week1);
week2 = ((week2 < 10 ? '0' : '') + week2)
var res = year1 + "-" + "W" + (week1); // ?
var res1 = year2 + "-" + "W" + (week2);
console.log(res, res1);}
In JS can use
https://momentjs.com/
This lib resolve your problem with any operations on the date
Change these two lines
var day1 = parseInt(d1.substring(6,)); //1
var day2 = parseInt(d2.substring(6,)); //5
Then it should work
but its better to work with Javascript Dates -> Good reference https://www.w3schools.com/js/js_dates.asp
Try this out.
I want to get complete years, (that contains 52 weeks ), so i used
year2-(year1+1),
So as to exclude both years, then i am adding year1 weeks (52-week1)
and then added week2
var year1 = d1.substring(0,4); //2017
var year2 = d1.substring(0,4); //2018
var week1 = d1.substring(6,); //01
var week2 = d2.substring(6,); //05
let result = 52 *( year2 - (year1 + 1) ) + (52 - week1) + week2
Hope, i could help you... I had use this in one of my project.
function diff_weeks(dt2, dt1){
var diff =(dt2.getTime() - dt1.getTime()) / 1000;
diff /= (60 * 60 * 24 * 7);
return Math.abs(Math.round(diff));
}
dt1 = new Date(2014,10,4);
dt2 = new Date(2014,10,12);
console.log(diff_weeks(dt1, dt2));
dt1 = new Date("June 4, 1990 08:11:00");
dt2 = new Date("October 10, 2018 11:13:00");
console.log(diff_weeks(dt1, dt2));
momentjs is the library you should use to manage date and time.
it will help you to manage each value of a date in a simple way.
var a = moment('2016-01-01');
var b = a.add(1, 'week');
a.format();
"2016-01-08T00:00:00-06:00"
See this examples:
https://codepen.io/bassfiddle/pen/lrLwy
This question already has answers here:
Get difference between 2 dates in JavaScript? [duplicate]
(5 answers)
Closed 5 years ago.
i am working on a date test javascript program that will let the user enter a date. It will parse the date to display the Month, day and year on separate lines with appropriate labels. It will also compare the current date with the entered date to display the number of day difference between them. So far I have been able to get the current dat to display and take users input but do not know how to calculate the number of days inbetween against the date I input. For some reason it is using the year 1969 I think to give me number of days difference and can not get it to parse into seperate lines. Have been working on this for weeks and is breaking my head on different ways to do so. So far I have the following:
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
var minutes = 1000 * 60;
var hours = minutes * 60;
var days = hours * 24;
var x = Math.round(da / days);
document.getElementById("dd").innerHTML = x;
}
</script>
Here is sample code
<header>
<h1>Date Test</h1>
</header>
<br>
<p>Please enter date:</p>
<input id="inp" type="date">
<br>
<br>
<button type="button" onclick="date_test()">Process</button>
<br>
<p id="iop"></p>
<br>
<p id="op"></p>
<br>
<p id="dd"></p>
<script>
document.getElementById("op").innerHTML = Date();
function date_test() {
var d = document.getElementById("inp").value;
document.getElementById("iop").innerHTML = d;
var inpu = document.getElementById("inp").value;
var da = Date.parse(inpu);
//here passing current date & selected date as params
console.log(daysBetween(new Date(), new Date(da)))
}
daysBetween = function( date1, date2 ) {
console.log(date1);
console.log(date2);
//Get 1 day in milliseconds
var one_day=1000*60*60*24;
// Convert both dates to milliseconds
var date1_ms = date1.getTime();
var date2_ms = date2.getTime();
// Calculate the difference in milliseconds
var difference_ms = date2_ms - date1_ms;
// Convert back to days and return
return Math.round(difference_ms/one_day);
}
</script>
Here is a simple function that you can use
function calculate_days(date1, dat2){
return (date2-date1)/(24*3600*1000);
}
date1 = new Date("4-4-2017");
date2 = new Date("4-8-2017");
console.log(calculate_days(date1, date2));
where date1 and date2 are date objects. 1000 in the denominator is needed as the difference would return number of milliseconds.
var date1 = new Date();
var dd = date1.getDate()+20; // add 20 days
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
date2 = new Date(yyyy+'/'+mm+'/'+dd);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
days = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log("day difference: ", days);
i think you should use these code
var date1 = new Date("7/20/2017");
var date2 = new Date("12/25/2017");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
I have 2 datetimepickers and I want to know to calculate the day or time.
Ex:
2017-01-12 09:00:00
2017-01-12 10:00:00
The answer should be 1:00:00
Below is my code. I also wanna know the date time formatting for this.
<input required type="text" class="form-control" id="time_in">
<input required type="text" class="form-control" id="time_out">
$start_time = $("#time_in").val();
$end_time = $("#time_out").val();
$answer = date_diff($start_time, $end_time)
alert($start_time);
This will do what you want to achieve.
Try:
old_date = "2010-11-10 07:00:00";
new_date = "2010-11-10 08:00:00";
old_date_obj = new Date(Date.parse(old_date, "dd/mm/yyyy HH:mm:ss"));
new_date_obj = new Date(Date.parse(new_date, "dd/mm/yyyy HH:mm:ss"))
t = (new_date_obj - old_date_obj);
seconds=(t/1000)%60
minutes=(t/(1000*60))%60
hours=(t/(1000*60*60))%24
alert(hours+":"+minutes+":"+seconds)
probably want something like
function date_diff(start, end)
{
var d1 = new Date(start);
var d2 = new Date(end);
return d2-d1;
}
note that the answer here is in miliseconds
var date;
date = new Date("$start_time);
var startTime = date.getTime();
date = new Date("$end_time);
var endTime = date.getTime();
var difference=startTime-endTime;
var answer= new Date(difference);
Hope this Helps.
I have a start-date and end-date and I want to calculate array of dates between these days based on a given duration.
for example,
if start date is 01/01/2015 and end date is 01/06/2015 and if I give duration as 3 months then out put should be:
01/04/2015
01/06/2015
How to achieve this using JavaScript and I need to display it in a form.
If you want to calculate difference between two dates using javascript:
Then,
function dateDiff() {
var dtFrom = document.getElementById('txtFromDate').value;
var dtTo = document.getElementById('txtToDate').value;
var dt1 = new Date(dtFrom);
var dt2 = new Date(dtTo);
var diff = dt2.getTime() - dt1.getTime();
var days = diff/(1000 * 60 * 60 * 24);
alert(dt1 + ", " + dt2);
alert(days);
return false;
}
function isNumeric(val) {
var ret = parseInt(val);
}
HTML:
<label for="txtFromDate">From Date : </label>
<input type="text" id="txtFromDate" name="txtFromDate" size="10" maxlength="10" value="03/25/2013"/><br/>
<label for="txtToDate">To Date : </label>
<input type="text" id="txtToDate" name="txtDate" size="10" maxlength="10" value="03/26/2013"/><br/>
<button id="btnCheck" name="btnCheck" onClick="dateDiff();" type="button">Difference</button>
AFTER EDIT:
Following solution is to get all dates between specified dates.
Working Demo
// using Datepicker value example code
$('#getBetween').on('click', function () {
var start = $("#from").datepicker("getDate"),
end = $("#to").datepicker("getDate");
var between = getDates(start, end);
$('#results').html(between.join('<br> '));
});
// This function doing this work.
function getDates(start, end) {
var datesArray = [];
var startDate = new Date(start);
while (startDate <= end) {
datesArray.push(new Date(startDate));
startDate.setDate(startDate.getDate() + 1);
}
return datesArray;
}
I have an input text that has a combination of date and time and display like this
04/01/2015 8:48PM
How can i convert this string to a date using the function new Date() in javascript? not output is shown
Here is what i've tried so far, i can only convert the date not the time.
HTML
<form name="frm1" >
<h3>Check in Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp1" /><br><br>
<h3>Check out Date:</h3>
<input type="text" value="" class="datetimepicker_mask" name="dtp2" /><br><br>
<input type="button" onclick="computeDate()" value="Compute Difference" />
<br><b>No of days: </b>
<span id="date_difference"></span>
</form>
JAVSCRIPT
function computeDate() {
var dateTime1 = document.frm1.dtp1.value;
var dateTime2 = document.frm1.dtp2.value;
var startDate = new Date(dateTime1);
var endDate = new Date(dateTime2);
var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
if (timeDiff == 0) {
timeDiff = 1;
}
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
var total = parseFloat(diffDays) * parseFloat(roomRate);
document.getElementById("date_difference").innerHTML = diffDays;
document.getElementById("date_difference").style.visibility = "visible";
}
If the date format is always the same, create a convience function that converts the date to a Date object
function convert(date) {
var dateArr = date.split(/[\s\/\:]/);
if (dateArr[4].toLowerCase().indexOf('pm') != -1)
dateArr[3] = (+dateArr[3]) + 12;
dateArr[4] = dateArr[4].replace(/\D/g,'');
dateArr[0]--;
return new Date(dateArr[2], dateArr[0], dateArr[1], dateArr[3], dateArr[4]);
}
FIDDLE
Here is an answer that will both solve this and make development easier. This suggestion will require an extra library for addressing such issues as you are having here- time, but you'll likely find it beneficial when working with JavaScript dates in general. It already looks like you're writing manual date functions. Abstract them away with robust libraries for solving these same issues that have come up again and again. Using date.js, here is how easy this becomes
Date.parse('04/01/2015 8:48PM ')
JSFiddle Example
You can create the Date object after parsing the dateString
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
you can use the parseDate function as following
var testDate = "04/01/2015 8:48PM";
console.log(parseDate(testDate));
function parseDate(dateStr){
var dateTime = dateStr.split(/\/| |:|(?=[PA])/);
for(var i=0; i<5; i++){
dateTime[i] = parseInt(dateTime[i]);
}
if(dateTime[5] == "PM"){
dateTime[3] += 12;
}
return new Date(dateTime[2], dateTime[1], dateTime[0], dateTime[3], dateTime[4]);
}
Try it at JSFiddle