Get Days and hours from two dates in js - javascript

I am trying to get Days,hours from two dates.I searched for the solution and try some code like below but none of them returns the correct days with hours like 2 days ,3 hours.My fields values are like :
d1 = '2014-10-09 08:10:56';
d2 ='2014-11-09 10:10:56';
var dateDiff = function ( d1, d2 ) {
var diff = Math.abs(d1 - d2);
if (Math.floor(diff/86400000)) {
return Math.floor(diff/86400000) + " days";
} else if (Math.floor(diff/3600000)) {
return Math.floor(diff/3600000) + " hours";
} else if (Math.floor(diff/60000)) {
return Math.floor(diff/60000) + " minutes";
} else {
return "< 1 minute";
}
};
function DateDiff(date1, date2) {
var msMinute = 60*1000,
msDay = 60*60*24*1000,
c = new Date(), /* now */
d = new Date(c.getTime() + msDay - msMinute);
return Math.floor(((date2 - date1) % msDay) / msMinute) + ' full minutes between'; //Convert values days and return value
}
what am i doing wrong.Any help thanks

Have you converted d1, d2 to Date object before calling the function dateDiff? Because if you haven't, this line var diff = Math.abs(d1 - d2); won't work as expected.
UPDATE:
I'am assuming your d1 and d2 are in "Y-m-d H:S:M" format, try this:
function parseDate(str){
var tmp = str.split(' ');
var d = tmp[0].split('-');
var t = tmp[1].split(':');
return new Date(d[0], d[1]-1, d[2], t[0], t[1], t[2]);
}
function dateDiff(d1, d2){
d1 = parseDate(d1);
d2 = parseDate(d2);
// ...
// Your code continues
}

I wish I could make it simpler... But this seems to work.
var d1 = '2014-10-09 08:10:58',
d2 ='2015-10-09 08:10:50';
function getDateFromString(str) {
var regexDate = /([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/,
values = regexDate.exec(str);
return new Date(values[1], values[2], values[3], values[4], values[5], values[6]);
}
function daysInMonth(month,year) {
return new Date(year, month, 0).getDate();
}
function dateDiff(d1,d2){
if (d1.getTime() > d2.getTime()) {
var oldD1 = d1;
d1 = d2;
d2 = oldD1;
}
var yearDiff = d2.getFullYear() - d1.getFullYear(),
monthDiff = d2.getMonth() - d1.getMonth(),
dayDiff = d2.getDate() - d1.getDate(),
hourDiff = d2.getHours() - d1.getHours(),
minDiff = d2.getMinutes() - d1.getMinutes(),
secDiff = d2.getSeconds() - d1.getSeconds();
if (secDiff < 0) {
secDiff = 60 + secDiff;
minDiff--;
}
if (minDiff < 0) {
minDiff = 60 + minDiff;
hourDiff--;
}
if (hourDiff < 0) {
hourDiff = 24 + hourDiff;
dayDiff--;
}
if (dayDiff < 0) {
var days = daysInMonth(date2.getMonth(), date2.getFullYear());
dayDiff = days + dayDiff;
monthDiff--;
}
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
var diff = yearDiff > 0 ? yearDiff + " years " : "";
diff += monthDiff > 0 ? monthDiff + " months " : "";
diff += dayDiff > 0 ? dayDiff + " days " : "";
diff += hourDiff > 0 ? hourDiff + " hours " : "";
diff += minDiff > 0 ? minDiff + " minutes " : "";
diff += secDiff > 0 ? secDiff + " seconds " : "";
return diff;
}
var date1 = getDateFromString(d1),
date2 = getDateFromString(d2)
document.getElementById('test').innerHTML += date1 + "<br />" + date2;
document.getElementById('test').innerHTML += "<br />" + dateDiff(date1, date2);
console.log(dateDiff(date1, date2));
See JSFiddle

It works in all browsers.
Try this - >
d1 = '2014-10-09 08:10:56';
d2 = '2014-11-09 10:10:56';
var diff = dateDiff(d1,d2);
alert(diff);
function splitDate(d1){
var dSplit = d1.split(' ');
d = dSplit[0] + 'T' + dSplit[1];
return d;
}
function dateDiff(d1,d2){
d1 = splitDate(d1);
d2 = splitDate(d2);
var date1 = new Date(d1);
var date2 = new Date(d2);
var dateDiff = new Date(date2 - date1);
var diff = "Month " + dateDiff.getMonth() + ", Days " + dateDiff.getDay() + ", Hours " + dateDiff.getHours();
return diff;
}

I am assuming you want the difference between 2 dates.
var dateDiff = function(d1/*String*/, d2/*String*/){
var date1 = new Date(d1);
var date2 = new Date(d2);
var result = {
negative:false
};
var diff = date1-date2;
if(diff<0){
result.negative = true;
diff*=-1;
}
result.milliseconds = diff%1000;
diff-=result.milliseconds;
diff/=1000;
result.seconds = diff%60;
diff-=result.seconds
diff/=60;
result.minutes = diff%60;
diff-=result.minutes
diff/=60;
result.hours = diff%24;
diff-=result.hours
result.days= diff/=24;
//And so on
return result;
}

I'm not sure if I really understood but I think this is what you want : http://jsfiddle.net/OxyDesign/927n0L34/
JS
var difference = toDaysAndHours('2014-10-09 08:10:56','2014-11-09 10:10:56');
function toDaysAndHours(d1,d2){
var dif, hours, days, difString = '';
d1 = new Date(d1);
d2 = new Date(d2);
dif = Math.abs(d1 - d2);
hours = (dif/(1000*60*60)).toFixed(0);
days = (hours/24).toFixed(0);
hours = hours - days*24;
difString = days+' days, '+hours+' hours';
return difString;
}

In the first function you are using strings not dates. to properly initialize a date use the constructor, as in:
d1 = new Date('2014-10-09 08:10:56')
d2 = new Date('2014-11-09 10:10:56')
Then on d1 and d2 you can use all of the get*/set* methods specified here: http://www.w3schools.com/jsref/jsref_obj_date.asp
While I got distracted writing the answer, I see others have said similar things, but I will add this:
The data object approach is good for understanding things, but if you want to save time use http://momentjs.com/ or a similar module to save time and mistakes.

Related

using javascript in html to display current date

I have this script which display Gregorian-Hijri date:
var fixd = document.getElementById('date');
function isGregLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 +
Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("محرم", "صفر", "ربيع الأول", "ربيع الثانى", "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة");
return this.day + " " + months[this.month - 1] + " " + this.year;
}
function fixedToHijri(f) {
var i = new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2 = new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
var tod = new Date();
var weekday = new Array("الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت");
var monthname = new Array("يناير", "فبراير", "مارس", "ابريل", "ماي", "جوان", "جويلية", "أوت", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + " " + d + " " + monthname[m] + " " + y);
m++;
fixd = gregToFixed(y, m, d);
var h = new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" / " + h.toString() + " ");
<div>
<ul>
<li id="date"></li>
</ul>
</div>
I want to use it in <li> tag
and if it is possible to display the date in two different positions at the same time at the same page
actually I am not familiar with java script so I don't know how to modify this script and then call it by id or whatever in html tag
any help please
This is really an extended comment.
The code can be considerably reduced by using the ca option with either toLocaleString or Intl.DateTimeFormat to set the calendar for formatted dates. It can also be used to set the language, e.g.
let d = new Date();
let options = {
year: 'numeric',
month: 'long',
day: 'numeric',
weekday: 'long'
};
console.log(
'Gregorian English: ' + d.toLocaleString('en-u-ca-gergory', options) + '\n' +
'Hijri English : ' + d.toLocaleString('en-u-ca-islamic', options) + '\n' +
'Hijri Arabic : ' + d.toLocaleString('ar-u-ca-islamic', options)
);
You can also use the formatToParts method to get the various parts and order or format them any way you wish.
You can set something like an attribute to any element that needs the date and then assign the innerHTML of that element.
This is all your code except I moved the 'loose' parts into a function that returns the finished date. Then this line
document.querySelectorAll('[display-date]')
.forEach(el => el.innerHTML = getTheDate())
says find all elements with the attribute display-date and insert the results of the date function in them
window.addEventListener('load', () => {
document.querySelectorAll('[display-date]').forEach(el => el.innerHTML = getTheDate())
})
function isGregLeapYear(year) {
return year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 +
Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("محرم", "صفر", "ربيع الأول", "ربيع الثانى", "جمادى الأولى", "جمادى الثانية", "رجب", "شعبان", "رمضان", "شوال", "ذو القعدة", "ذو الحجة");
return this.day + " " + months[this.month - 1] + " " + this.year;
}
function fixedToHijri(f) {
var i = new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2 = new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
function getTheDate() {
var tod = new Date();
var weekday = new Array("الأحد", "الإثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت");
var monthname = new Array("يناير", "فبراير", "مارس", "ابريل", "ماي", "جوان", "جويلية", "أوت", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
let d1 = (weekday[dow] + " " + d + " " + monthname[m] + " " + y);
m++;
fixd = gregToFixed(y, m, d);
var h = new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
let d2 = " / " + h.toString() + " ";
return d1 + d2;
}
<div>
<ul>
<li display-date class="date"></li>
</ul>
</div>
<h3 display-date></h3>
<p>Todays date is <span display-date></span></p>

Calculate datetime with javascript in days

I have a date in datetime and I need to calculate it with the current date in javascript to check if 7 days have passed.
var created_at = 2021-05-20; //return 2021-05-20 14:00:00
var data = new Date();
var dataAtual = data.getFullYear() + "-" + ("0" + (data.getMonth() + 1)).substr(-2) + "-" + ("0" + data.getDate()).substr(-2);
var result = data - created_at;
if(result < 7){
var create_date = true;
console.log(true);
} else {
var created_date = false;
console.log(false);
}
Can you try the below code
var date1 = new Date('2021-05-20 14:00:00')
var date2 = new Date()
var resulu = date2.getDate() - date1.getDate()
if(result < 7){
var create_date = true;
console.log(true);
} else {
var created_date = false;
console.log(false);
}
Get the difference of dates in milliseconds and convert into days.
const old_date = new Date('2021-05-20');
const today = new Date();
const diff_days = (today - old_date) / 24 * 60 * 60 * 1000;
if (diff_days < 7) {
console.log('older than a week');
} else {
console.log('in last week');
}

How to check if current time falls within a specific range considering also minutes

I am doing a Website for Restaurants Home Delivery ,depending on Restaurant's Home Delivery Timings i need to enable / disable Order Now Button
I have got startTime and End Time in 12 Hour format .
This is the code
var startTime = '8:30 AM' ;
var endTime = '6:30 PM' ;
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"),hours24>11?"pm" :"am"].join(" ");
}
return formatted;
}
})();
var currentTime = formatTime(new Date());
I need to check if the current time is in between startTime and EndTime or not
If its only Hours ,i could have extracted the first character before colon from startTime ,endTime and currentTime and done a comparision like this
if(currentTime >= startTime && currentTime <= endTime)
{
alert('Restaurant Open');
}
else
{
alert('Restaurant Closed');
}
But i need to take the minutes also in consideration ,so could you please let me how to do this comparsion if minutes were takein in consideration ??
How to check if current time falls within a specific range considering also minutes
Something like this should work
var startTime = '6:30 PM';
var endTime = '8:30 AM';
var now = new Date();
var startDate = dateObj(startTime); // get date objects
var endDate = dateObj(endTime);
if (startDate > endDate) { // check if start comes before end
var temp = startDate; // if so, assume it's across midnight
startDate = endDate; // and swap the dates
endDate = temp;
}
var open = now < endDate && now > startDate ? 'open' : 'closed'; // compare
console.log('Restaurant is ' + open);
function dateObj(d) { // date parser ...
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
.as-console-wrapper {top : 0!important}
It splits those times and adds 12 to PM times, then creates date objects that can easily be compared.
Doesn't seem to work with times passing midnight, try changing the time from 6:30PM to 2:30AM. A good solution is to use momentjs with the moment-range plugin
function inTimeRange(time, startTime, endTime)
{
//Setup today vars
var today = new moment(new Date());
var ayear = today.year();
var amonth = today.month() + 1; // 0 to 11
var adate = today.date();
amonth = String(amonth).length < 2 ? "0" + amonth : amonth;
adate = String(adate).length < 2 ? "0" + adate : adate;
//Create moment objects
var moment1, moment2;
var temp = endTime.split(" ");
if(temp[1].toLowerCase() == "am")
{
var test1 = ayear + "-" + amonth + "-" + adate + " " + startTime;
var test2 = ayear + "-" + amonth + "-" + adate + " " + endTime;
//Make sure that both times aren't morning times
if(moment(test2).isAfter(test1))
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + adate + " " + endTime;
}
else
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + (adate + 1) + " " + endTime;
}
moment1 = moment(moment1String, "YYYY-MM-DD HH:mm A");
moment2 = moment(moment2String, "YYYY-MM-DD HH:mm A");
}
else
{
var moment1String = ayear + "-" + amonth + "-" + adate + " " + startTime;
var moment2String = ayear + "-" + amonth + "-" + adate + " " + endTime;
moment1 = moment(moment1String, "YYYY-MM-DD HH:mm A");
moment2 = moment(moment2String, "YYYY-MM-DD HH:mm A");
}
//Run check
var start = moment1.toDate();
var end = moment2.toDate();
var when;
if(String(time).toLowerCase() == "now")
{
when = moment(new Date());
}
else
{
var timeMoment1String = ayear + "-" + amonth + "-" + adate + " " + time;
when = moment(timeMoment1String);
}
var range = moment().range(start, end);
return when.within(range);
}
var startTime = '02:30 AM';
var endTime = '13:00 PM';
var now = new Date();
var startDate = dateObj(startTime);
var endDate = dateObj(endTime);
alert(endDate)
var open = now < endDate && now > startDate ? 'open' : 'closed';
alert('Restaurant is ' + open);
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
var startTime = '8:30 AM';
var endTime = '6:30 PM';
var now = new Date();
var startDate = dateObj(startTime);
var endDate = dateObj(endTime);
var open = now < endDate && now > startDate ? 'open' : 'closed';
alert('Restaurant is ' + open);
function dateObj(d) {
var parts = d.split(/:|\s/),
date = new Date();
if (parts.pop().toLowerCase() == 'pm') parts[0] = (+parts[0]) + 12;
date.setHours(+parts.shift());
date.setMinutes(+parts.shift());
return date;
}
I have done something similar to this. My app was receiving times in military time. So in the case where times didn't pass into the next day (i.e. start time of 09:00 and end time of 17:00 you would just check if you are between those times.
In the case of the end time being after midnight (i.e. start time of 15:00 and end time of 01:00) then there are three cases:
You are in a time after both start and end times, like 16:00, in which case you are inside business hours
You are in a time before both start and end times, like 00:30, in which case you are also inside business hours.
You are in a time after the end time, but before the start time, like 02:30, in which case you are outside of business hours
Here is my code sample:
const isCurrentDayPart = (dayPart) => {
let currentTime = moment();
let startTime = moment(dayPart.startTime, "HH:mm");
let endTime = moment(dayPart.endTime, "HH:mm");
if (dayPart.startTime < dayPart.endTime) {
return currentTime.isBetween(startTime, endTime);
} else {
if (currentTime.isAfter(endTime) && currentTime.isAfter(startTime)) {
return true;
} else if (currentTime.isBefore(endTime) && currentTime.isBefore(startTime)) {
return true;
}
}
return false;
};

Displaying the time in 12hr format

I need your help
If the code below is able to get the date in my requested format of: dd/mm/yyyy
How do I go about getting the time in a 12hr format ie. 13:53 is 1:53pm
Thank you
<script type="text/javascript">
function test() {
var d = new Date(),
m = d.getMonth() + 1,
xdate = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/');
var t = d.format("h:mm ss");
alert("the date is:" + xdate + "time is:" + t)
}
</script>
Demo jsFiddle
JS
var d = new Date();
alert("the date is: " + d.toLocaleDateString() + "time is: " + d.toLocaleTimeString());
Note: these functions aren't exactly cross browser supported
Use this:
var d = new Date(),
m = d.getMonth()+1,
x = [d.getDate(), (m < 10) ? '0' + m : m, d.getFullYear()].join('/'),
y = d.toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3")
alert(x +" "+ y)
Taken from:
How do you display javascript datetime in 12 hour AM/PM format?
It is not that difficult. Try this one out :
JS:
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = dt.getHours();
var hours = ((hours24 + 11) % 12) + 1;
formatted = [formatted, [addZero(hours), addZero(dt.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
return formatted;
}
})();
console.log(formatTime(new Date()));
Find the working fiddle here : http://jsfiddle.net/rRd2P/1/

javascript Date Object how long ago

I'm trying to show how long ago a video was uploaded, i cant seem to get the hours and minutes Date Object Methods to work in this script. I'm working of a script called YouMax 2.0 and i have been editing the function getDateDiff, i have come up with this edit of the function. Thank you for any help on this.
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 d1T = d1.getMinutes();
var d2T = parseInt(splitTime[1], 10);
var diffInMinutes = (d1T + 59 * d1H + 23) - (d2T + 59 * d2H + 23);
if (diffInMinutes <= 1) return "1 Minute";
else if (diffInMinutes <= 59) return diffInMinutes + " Minutes";
var diffInHours = (d1H + 23 * d1M) - (d2H + 23 * d1M);
if (diffInHours <= 1) return "1 Hour";
else if (diffInHours < 23) return diffInHours + " Hours";
var diffInDays = (d1D + 30 * d1M + 12 * d1Y) - (d2D + 30 * d2M + 12 * d2Y);
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";
}
my new function only returns minutes and other and wont update to change of day
I assume you are fetching the timestamp from a mysql database. This was also answered here. The top answer is in php but it is not really different from Javascript. I do suggest using php for this however.
you can see that your splitting was not correct...
this is working fine..
var splitDate = ((timestamp.toString().split('T'))[0]).split('-');
var splitTime = ((timestamp.toString().split('T'))[1]).split(':');
var splitTime1 = ((splitTime[2].toString().split('Z'))[0]).split('.');
splitDate[0] = Year;
splitDate[1] = Month;
splitDate[2] = Day;
splitTime[0] = Hours;
splitTime[1] = Minutes;
splitTime1[0] = Seconds;
splitTime1[1] = MilliSeconds;
you can now perform what ever you want to..

Categories

Resources