UTC time in javascript 48 hours if month is changed - javascript

For one or another reason this code sample gives 48 hours instead of 24, can anyone explain me why the UTC time of a new month in javascript bugs orw hat I am doing wrong? Thanks for helping me out.
<script type="text/javascript">
function myFunction()
{
var d = (Date.UTC(2012,07,01) - Date.UTC(2012,06,30)) / 1000 / 3600;
alert(d);
}
myFunction();
</script>

Because month 6 is July, since months are zero-based in JavaScript dates, and there are 31 days in July.
If you want the number of hours between July 1st and June 30th, you want:
var d = (Date.UTC(2012,06,01) - Date.UTC(2012,05,30)) / 1000 / 3600;
or more generally:
function hoursBetween(startYear, startMonth, startDay, endYear, endMonth, endDay){
var d1 = Date.UTC(startYear, startMonth-1, startDay );
var d2 = Date.UTC(endYear, endMonth-1, endDay );
return (d2-d1)/(3600*1000);
}
For more information, read the documentation on Date.UTC.

Related

How to subtract 5 days from a defined date - Google App Script

I'm trying to write a script to subtract 5 days from a defined date but seems not working, here's my code:
var End_Day = sheet.getRange(i + 2, 20).getValue();
Logger.log(End_Day);
var End_day_2 = new Date();
End_day_2.setDate(End_Day.getDate()-5);
Logger.log(End_day_2);
and the result is not just - 5 days:
11:18:47 AM Info Sat Jun 04 00:00:00 GMT+08:00 2022
11:18:47 AM Info Fri Apr 29 11:18:47 GMT+08:00 2022
I am quite confused why the date move from Jun to Apr.
Thanks for having a look
Try:
var End_Day = sheet.getRange(i + 2, 20).getValue();
var End_day_2 = new Date(End_Day.getTime() - (5 * (1000 * 60 * 60 * 24)))
Logger.log(End_Day);
Logger.log(End_day_2);
Function:
const endDay = sheet.getRange(i + 2, 20).getValue()
const endDay2 = DateFromDaysAgo(endDay, 5)
...
function DateFromDaysAgo(startDate, number) {
if (typeof startDate === `string`) { startDate = new Date(startDate) }
return new Date(startDate.getTime() - (number * (1000 * 60 * 60 * 24)))
}
You should learn more about Date.prototype.setDate().It only changes the day of the month of a given Date instance.
As the code you posted, the day of the month of End_Day is 4, End_day_2.setDate(4 - 5) equals to End_day_2.setDate(-1) and the month of End_day_2 is April according to the console result, because there're 30 days in April, setDate(-1) means setDate(29), so you got Apr 29 at the end. That's how it goes.
One right way to do is substracting 5 days worth of milliseconds.
function addDays(date, days){
const DAY_IN_MILLISECONDS = 24 * 60 * 60000;
return new Date(date.getTime() + days * DAY_IN_MILLISECONDS);
}
console.log(addDays(new Date(), -5).toString()); // 5 days ago
I am quite confused why the date move from Jun to Apr.
It's because you're setting date on today(End_day_2) and not on your predefined date(End_day).
Change
End_day_2.setDate(End_Day.getDate()-5);
to
End_Day.setDate(End_Day.getDate()-5);
console.info(End_Day);
If what's coming from the sheet is a string, you will have to convert the date string into a date object.
The other thing is you have to work in milliseconds as #vanowm says:
606024*5 = 432000 * 1000 = 432000000
so skipping the sheet entirely:
x = new Date
> Fri May 27 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
y = new Date(x - 432000000)
> Sun May 22 2022 11:24:01 GMT-0400 (Eastern Daylight Time)
This will do the trick. Works with any date and can subtract any number of days
const subtractDays = (fromDate, numDays) => {
if (!(fromDate instanceof Date)) throw 'The first argument must be a date';
return new Date(new Date().setDate(fromDate.getDate() - +numDays));
};
Weekago
function weekago() {
let dt = new Date();
dt.setDate(dt.getDate()-7);
Logger.log(dt);
return dt;
}
Five days ago
function fiveago() {
let dt = new Date();
dt.setDate(dt.getDate()-5)
Logger.log(dt);
return dt;
}
Five days from a date in a spreadsheet cell
function fivefromadateinspreadsheet() {
const v = SpreadsheetApp.getActiveSheet().getRange("A1").getValue();
let dt = new Date(v);
dt.setDate(dt.getDate()-5);//Note that does not return a date it return the numbrer of milliseconds
Logger.log(dt);
return dt;
}
You can subtract 5 days from a defined date in Google App Script by using the Utilities.formatDate() method. Here's an example:
function subtractDays() {
var date = new Date();
var subtractDays = 5;
// Subtract 5 days from the current date
date.setDate(date.getDate() - subtractDays);
// Format the new date
var newDate = Utilities.formatDate(date, "UTC", "yyyy-MM-dd");
Logger.log(newDate);
}
In this example, we first create a Date object to represent the current date. Then, we subtract 5 days from the current date by using the setDate() method. Finally, we format the new date using the Utilities.formatDate() method and log it to the console using the Logger.log() method.
You can modify the subtractDays variable to subtract a different number of days from the date, or you can use a different date object to start with.

How does momentjs handle addition or subtraction in terms of months or year

My question is how does momentjs handle addition or subtraction in terms months or years when there is a leap year or months that have different days in them such as March has 31 days and April has 30 days
An example is does it set it months to 30.4167 days by default or does it do some calculations on how many days will be in a month in different years or the difference of how many days there will be between March or April
moment().add(1, 'months'); is this equal to 30.4167 days for every month or 730.001 hours for every month?
How is momentjs handling this
Without moment.js, this solution seems to work well.
Basically set the month to the current month + the number of months.
One problem this causes is that adding 1 month to say 31st, and the next month only had 30, would give you the 1st of the next month.
To fix this, you can check for it. If the new day of the month is different to the original, then we overflowed and we can just set the day to 1 and subtract 1 day to handle this.
Below is an example, if you run you will also see 28 & 29 of Feb with the leap year difference.
const aday = 1000 * 60 * 60 * 24;
function addMonth(dt, m) {
const r = new Date(dt);
r.setMonth(r.getMonth() + m);
if (dt.getDate() !== r.getDate()) {
r.setDate(1);
r.setTime(r.getTime() - aday);
}
return r;
}
const first = new Date("2019-12-31");
for (let l = -10; l < 10; l += 1) {
const second = addMonth(first, l);
console.log(`${second.toDateString()} - ${l} months`);
}
var currentDate = moment('2015-11-31');
var addMonth = moment(currentDate).add(1, 'M');
for years
var addYear = moment(currentDate)..add('years', 1).format('L');

JS/PHP, time of date

i would like to ask, if someone know to to make in JS or PHP time of date.
Or how long we're together, like 70 days or 2 month and some days, and all day add 1 more day. I have something whats work, but on begging of that time is - .
I spent a lot time with making something what should work. But nothing.
There is that code with that -
<script charset="UTF-8">
function daysTill() {
var day= 8
var month= 12
var year= 2016
var event= "relationship with my ♥"
var end = "days of"
var daystocount=new Date(year, month -1, day)
today=new Date()
if (today.getMonth()==month && today.getDate()>day)
daystocount.setFullYear(daystocount.getFullYear())
var oneday=1000*60*60*24
var write = (Math.ceil((daystocount.getTime()-today.getTime())/(oneday)))
document.write('<strong>'+write +'</strong> '+end+' '+event)
}
daysTill();
</script>
if someone know, please help me. Thanks ♥
The getTime() method returns the time in milliseconds so to convert it to days you divide that by 86400000 (1000 for seconds * 60 for minutes * 60 for hours * 24 for days):
var relationship = new Date("2016/12/08");
var today = new Date();
var days = Math.ceil((today.getTime() - relationship.getTime()) / 86400000);
document.write(days + " days have pass since the start of the relationship.");
Try to use "JavaScript date maths"
// new Date(year, month (0-11!), day, hours, minutes, seconds, milliseconds);
var dateFuture = new Date(2017, 3, 1, 9, 0, 0, 0);
var dateLongAgo = new Date(2001, 8, 11, 8, 46, 0, 0);
var dateNow = new Date();
//86400000 millis per day
//floor --> all unter a full day shall be 'no day'
var daysSince = Math.floor((dateNow-dateLongAgo)/86400000);
var daysUntil = Math.floor((dateFuture-dateNow)/86400000);
console.log("long ago\t", dateLongAgo);
console.log("now is\t\t",dateNow);
console.log("then\t\t",dateFuture);
console.log("days since\t",daysSince);
console.log("days until\t", daysUntil);
If you don't mind using external libraries, Carbon is a nice tool extending DateTime
http://carbon.nesbot.com/docs/
It returns many kinds very nicely formatted dates -- months, days, hours etc included.

How to get total number of hours between two dates in javascript?

I am in a situation where I need to find out the total hour difference between two date objects but the thing is dates aren't present in the actual format.
Date 1: 6 Apr, 2015 14:45
Date 2: 7 May, 2015 02:45
If it would have been in standard format, simply I would have been used below method:
var hours = Math.abs(date1 - date2) / 36e5;
I am not sure how do I get the hour difference here... please help.
You can create date objects out of your strings:
const dateOne = "6 Apr, 2015 14:45";
const dateTwo = "7 May, 2015 02:45";
const dateOneObj = new Date(dateOne);
const dateTwoObj = new Date(dateTwo);
const milliseconds = Math.abs(dateTwoObj - dateOneObj);
const hours = milliseconds / 36e5;
console.log(hours);
You can create two date objects from the strings you have provided
var date1 = new Date("6 Apr, 2015 14:45");
var date2 = new Date("7 May, 2015 02:45");
then you can simply get the timestamp of the two dates and find the difference
var difference = Math.abs(date1.getTime() - date2.getTime());
Now to convert that to hours simply convert it first to seconds (by dividing by 1000 because the result is in milliseconds), then divid it by 3600 (to convert it from seconds to hours)
var hourDifference = difference / 1000 / 3600;
var date1 = new Date("6 Apr, 2015 14:45").getTime() / 1000;
var date2 = new Date("7 May, 2015 02:45").getTime() / 1000;
var difference = (date2 - date1)/60/60;
console.log(difference); //732 hours or 30.5 days
I'm not sure what you mean, but this works for me.
<!DOCTYPE html>
<html>
<body>
<p id="hours"></p>
<script>
var d1 = new Date("1 May, 2015 14:45");
var d2 = new Date("29 April, 2015 14:45");
var hours = (d1-d2)/36e5;
document.getElementById("hours").innerHTML = hours;
</script>
</body>
</html>

How to get difference between 2 Dates in Years, Months and days using moment.js

How to get difference between 2 Dates in Years, Months and days using moment.js?
For example the difference between 4/5/2014 & 2/22/2013 should be calculated as 1 Year, 1 Month and 14 Days.
Moment.js can't handle this scenario directly. It does allow you to take the difference between two moments, but the result is an elapsed duration of time in milliseconds. Moment does have a Duration object, but it defines a month as a fixed unit of 30 days - which we know is not always the case.
Fortunately, there is a plugin already created for moment called "Precise Range", which does the right thing. Looking at the source, it does something similar to torazaburo's answer - but it properly accounts for the number of days in the month to adjust.
After including both moment.js and this plugin (readable-range.js) in your project, you can simply call it like this:
var m1 = moment('2/22/2013','M/D/YYYY');
var m2 = moment('4/5/2014','M/D/YYYY');
var diff = moment.preciseDiff(m1, m2);
console.log(diff);
The output is "1 year 1 month 14 days"
You hardly need moment.
d1 = new Date(2014, 3, 5); // April 5, 2014
d2 = new Date(2013, 1, 22); // February 22, 2013
diff = new Date(
d1.getFullYear()-d2.getFullYear(),
d1.getMonth()-d2.getMonth(),
d1.getDate()-d2.getDate()
);
This takes advantage of the fact that the Date constructor is smart about negative values. For instance, if the number of months is negative, it will take that into account and walk back the year.
console.log(diff.getYear(), "Year(s),",
diff.getMonth(), "Month(s), and",
diff.getDate(), "Days.");
>> 1 Year(s), 1 Month(s), and 11 Days.
Your calculation is wrong--it's not 14 days, it's six remaining days in February and the first five days of April, so it's 11 days, as the computer correctly computes.
Second try
This might work better given #MattJohnson's comment:
dy = d1.getYear() - d2.getYear();
dm = d1.getMonth() - d2.getMonth();
dd = d1.getDate() - d2.getDate();
if (dd < 0) { dm -= 1; dd += 30; }
if (dm < 0) { dy -= 1; dm += 12; }
console.log(dy, "Year(s),", dm, "Month(s), and", dd, "Days.");
This worked for me. Verified with Age calculator.
function calculateAge(){
ageText = jQuery("#dob").closest(".form-group").find(".age-text");
ageText.text("");
level2.dob = jQuery("#dob").val();
if(!level2.dob) return;
level2.mdob= moment(level2.dob, 'DD-MM-YYYY');
if(!level2.mdob.isValid()){
alert("Invalid date format");
return;
}
level2.targetDate = moment();//TODO: Fill in the target date
level2.months = level2.targetDate.diff(level2.mdob, 'months'); // Calculate the months
let years = parseInt(level2.months/12); // A year has 12 months irrespective or leap year or not
let balanceMonths = level2.months%12; // The balance gives the number of months
let days;
if(!balanceMonths){ // If no balance months, then the date selected lies in the same month
months = 0; // so months = 0
days = level2.targetDate.diff(level2.mdob, 'days'); // only the days difference
}else{
months = balanceMonths;
dob_date = level2.mdob.date();
target_month = level2.targetDate.month();
construct_date = moment().month(target_month).date(dob_date);
days = level2.targetDate.diff(construct_date, 'days')+1; // There might be one day missed out. Not sure on UTC
}
ageText = years +" years " + months+ " months " + days +" days";
}

Categories