Moment js format with over24 hours fails [duplicate] - javascript

This question already has answers here:
Get the time difference between two datetimes
(22 answers)
Closed 3 years ago.
AM trying to format momentjs to hh:mm:ss in over 24 hours but i only get 1 hour so i have tried
const start = moment('2019-02-27 00:00');
const end = moment('2019-03-01 01:00');
var diff =end.diff(start, 'seconds', true)
let ff = moment.utc((diff) * 1000).format('HH:mm:ss')
console.log(ff)
In the above i expected to get
49:00:00
as its two days and 1 hour so 24*2 since each day has 24 hours plus the one hour from 00:0 to 01:00
WHere am i going wrong as it shows 01:00:00 instead of 49:00:00

Also run into the same problem, heres my code snippet if that would help you.
let start = moment('2019-03-01 00:00:00');
let stop = moment();
const formatTimespan = (start, stop) => {
const diff = stop.diff(start, "hours", true);
const hours = Math.floor(diff);
const step = 60 * (diff - hours)
let mins = Math.floor(step)
let secs = Math.floor(60 * (step - mins));
mins = mins.toString().padStart(2, "0");
secs = secs.toString().padStart(2, "0");
return `${hours}:${mins}:${secs}`;
}
console.log(formatTimespan(start, stop));

Related

Calculating time elapsed javascript wrong output

I am currently using a script to calculate the time passed in years, months, days etc in Javascript.
$(document).ready(function(){
var birth_date = new Date('March, 25, 2022');
var years,months,days, hours, minutes, seconds;
var ageCount = document.getElementById('counter');
setInterval(function(){
var current_date = new Date();
var YearDiff = (current_date.getYear() - birth_date.getYear());
var monthDiff = (current_date.getMonth() - birth_date.getMonth());
var daysDiff = (current_date.getDate() - birth_date.getDate());
var hoursDiff = (current_date.getHours() - birth_date.getHours());
var minDiff = (current_date.getMinutes() - birth_date.getMinutes());
var secDiff = (current_date.getSeconds() - birth_date.getSeconds());
ageCount.innerHTML=YearDiff+' Years '+monthDiff+' Months '+daysDiff+' Days '+hoursDiff+
' Hours '+minDiff+' Minutes '+secDiff+' Seconds';
},500);
});`
This seems to output the right months, days and hours when the set date day is lower than the current date (so April 21 when it is now April 22).
0 Years 1 Months 2 Days 8 Hours 14 Minutes 2 Seconds`
When the date day number is higher, it changes it to a certain number of months minus a number of days. Like this (1 month - 4 days, when it should just be 0 months and 27 days).
0 Years 1 Months -4 Days 8 Hours 14 Minutes 38 Seconds
An example of the script is viewable here: https://jsfiddle.net/j2k7n4zp/
Does anyone have a clue what goes wrong or what I need to fix to make it calculate the right amount of days without using minus?
Thanks in advance!
What's going wrong with your code is that assume every part of a later date is higher than every part of an earlier one ... e.g. ... 23 April 2022 to 1 May 2022 - the Date is lower, but the Month is higher - whereas your code naively the Date portion of 1 May is Higher than 23 April just because May is later than April - but that's not how dates work
Here's something I literally whipped up now, see if it helps
const dateDiff = (from, to) => {
// so we don't mutate passed in dates
let start = new Date(from);
let end = new Date(to);
if (+start > +end) {
[start, end] = [end, start];
}
const loop = (prop) => {
const set = `set${prop}`;
const get = `get${prop}`;
let ret = 0;
while (1) {
start[set](start[get]() + 1);
if (start < end) {
ret++;
} else {
start[set](start[get]() -1);
break;
}
}
return ret;
}
const years = loop('FullYear');
const months = loop('Month');
const days = loop('Date');
const hours = loop('Hours');
const minutes = loop('Minutes');
const seconds = loop('Seconds');
const milliseconds = loop('Milliseconds');
return {years, months, days, hours, minutes, seconds, milliseconds}
}
const ageCount = document.getElementById('counter');
setInterval(() => {
const r = dateDiff(new Date(), new Date('2022-03-25'));
ageCount.innerHTML = `${r.years} Years, ${r.months} Months, ${r.days} Days, ${r.hours} Hours, ${r.minutes} Minutes, ${r.seconds} Seconds`;
}, 500);
<div id="counter">
</div>

date time in javascript [duplicate]

This question already has answers here:
How to calculate the number of days between two dates? [duplicate]
(7 answers)
Closed 10 months ago.
I have a code script to calculate the number of days between today and an expected day:
let date1 = new Date(); //today
let date = new Date("04/19/2022") //expected day
let differenceInTime = date1.getTime() - date.getTime(); //difference by milliseconds
let differenceInDay = (differenceInTime - differenceInTime%(1000 * 3600 * 24))/(1000 * 3600 * 24); // JS does not supports dividing by whole so I implement this to get the number of days
The result is true for every cases, except that when I choose the day after today (tomorrow) as expected day, the result also is 0. Is there something not exact in my code?
the problem with your code is that on line 4 you kinda fix the differenceInTime to 0 decimals and difference between the expected day and today is less than 1 in days, so It'll be truncated.
You can do it easier this way. using Math methods or num.toFixed()
your code will be shorter and cleaner.
you don't even need date.getTime() cause date will automatically
convert to ms when you do mathematical operations on it.
let date1 = new Date(); //today
let date = new Date("04/20/2022"); //expected day
let differenceInMS = date1 - date; //difference in ms
let differenceInDay = (differenceInMS / 8.64e7).toFixed(1); // 8.64e+7 : a day in ms
console.log(differenceInDay);
Convert to Millisecond and then perform same logic

How can I get the first and last day of the week crossing months in javascript [duplicate]

This question already has answers here:
How to get first and last day of the current week in JavaScript
(32 answers)
Closed 2 years ago.
So for example, monday is sep 28, a week from monday, sunday is oct 4. How Can I get the first and last day of the week? So far the solutions cover only days belonging in the same month. Please help. Thanks
You can use date-fns library for that:
const start = startOfWeek(date);
const end = endOfWeek(date);
Check out these threads for more solutions:
How to get first and last day of current week when days are in different months?
How to get first and last day of the week in JavaScript
You want to look into the Date.getDay() method. This returns a number from 0-6 for the day of the week (Sunday is 0).
As a function, it could look like this:
function getMonday(date){
const originalDay = date.getDay();
const monday = 1;
const newDate = new Date(date);
const delta = originalDay === 0 ? 1 : originalDay - monday;
newDate.setDate(newDate.getDate() - delta);
return newDate;
}
You can add a week to the starting date's time and construct a new date:
const DAY = 1000 * 60 * 60 * 24; // ms * seconds * minutes * hours
const WEEK = DAY * 7;
const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);
console.log(nextWeek.toUTCString());
Then add or subtract from that date to get the first/last day of the week if necessary.
const DAY = 1000 * 60 * 60 * 24;
const WEEK = DAY * 7;
const today = new Date('2020-09-29');
const nextWeek = new Date(today.getTime() + WEEK);
const day = nextWeek.getDay(); // 0 sunday, 6 saturday
const firstDay = new Date(nextWeek.getTime() - (day * DAY));
const lastDay = new Date(nextWeek.getTime() + ((6 - day) * DAY));
console.log(firstDay.toUTCString()); // monday
console.log(lastDay.toUTCString()); // sunday

Javascript: convert number of days to years, months and days

I have days, months and years. I'm doing calculations between them. That means I have to divide 2 years 3 months and 10 days by 1/4. Now i have following code:
const getCurrentDate = moment().format("YYYY-MM-DD");
const timeEnd = moment(moment(DefEndDate).format("YYYY-MM-DD"));
const diff = timeEnd.diff(getCurrentDate);
const diffDuration = moment.duration(diff);
const diffCount = moment.duration(diff).asDays();
console.log(diffCount);
console.log("Years:", diffDuration.years());
console.log("Month:", diffDuration.months());
console.log("Days:", diffDuration.days());
const diffCount = moment.duration(diff).asDays(); //Get it as days
const [unserve, setUnserve] = useState(''); //set value to variable
const res = unserve.split('/'); //split 1/4 to 1.4
const x = parseFloat(res[0] + "." + res[1]); //convert it to float
var quotient = Math.floor(diffCount/x); //calculate
console.log(quotient);
//returned 832 / 1.4 = 594 days
Now I need to return the output number (days) to the year, month and day. I can't do that. How do I convert? And another question is, can this way be the optimal solution?
I can't decide whether what you really want to do is divide a date range in to a fixed number of periods with equal days, or to start with a date, add a period in years, months and days to get an end date, then divide that into equal periods.
The following assumes the latter.
I have to divide 2 years 3 months and 10 days by 1/4
The number of days covered by that period varies depending the dates it is to and from, so you have to start with the start and end dates of the range.
In your code:
const getCurrentDate = moment().format("YYYY-MM-DD");
Sets getCurrentDate to a string like 2020-02-11.
const timeEnd = moment(moment(DefEndDate).format("YYYY-MM-DD"));
Creates a moment object from the string value of getCurrentDate and sets timeEnd to another string.
const diff = timeEnd.diff(getCurrentDate);
This attempts to call the diff method of timeEnd, which is a string. Strings don't have a diff method so the expression returns undefined, attempting to call it throws an error something like TypeError: '2020-02-11'.diff is not a function.
The rest of your code seems to be based on a algorithm
If you have a predetermined period in years, months days, etc. you can start with a start date, add the period, then get the number of days difference. Divide that difference by the number of periods you want, then add that sequentially to get the various end dates.
The following example uses moment.js since that's what you appear to be using, however a version without a library is about the same difficulty. It returns an array of dates, starting with the start date so there is one more date than periods.
function getDates(
start = new Date(),
years = 0,
months = 0,
days = 0,
parts = 1) {
// Get start and end as moment objects
let m = moment(start).startOf('day');
let end = moment(m);
end.add({years:years, months:months, days:days});
// Get days difference and number of days to add for each period
let daysDiff = end.diff(m, 'days');
let f = daysDiff / parts;
let dayArray = [m.format('YYYY-MM-DD')];
let i = 0;
while ((f * ++i) <= daysDiff) {
let d = moment(m).add(f * i, 'days')
dayArray.push(d.format('YYYY-MM-DD'));
}
return dayArray;
}
// Get dates for 4 even periods over 2 years, 3 months and
// 10 days from today
console.log(getDates(new Date(), 2, 3, 10, 4));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
As the sub–period length is nearly always not an even number of days (in the above case it's about 207.5), I've allowed formatting to effectively truncate the decimal part of a day. You might want to use some other rounding algorithm that more evenly distributes the remainder.
If, on the other hand, you have start and end dates and want an equal number of periods, the following is much simpler (and doesn't use a library):
// Helpers - use UTC do avoid DST issues
function toUTCDate(s) {
let b = s.split(/\D/);
return new Date(Date.UTC(b[0], --b[1], b[2]));
}
function formatUTC(date) {
return date.toISOString().substr(0, 10);
}
/* #param {string} start - date string in format 'YYYY-MM-DD'
** #param {string} end - date string in format 'YYYY-MM-DD'
** #param (numbe} n - number of required periods
** #returns {Array} array of date strings in format 'YYYY-MM-DD'
*/
function periods(start, end, n) {
let s = toUTCDate(start);
let e = toUTCDate(end);
let diff = e - s;
let f = diff / n;
let result = [formatUTC(s)];
// Allow for rounding of decimal f in comparison
while (e - s > n) {
s.setTime(s.getTime() + f);
result.push(formatUTC(s))
}
return result;
}
console.log(periods('2020-02-09','2022-05-19', 4));
The two methods produce slightly different results, you'll need to work out if that matters or not.
Long time ago I used such code to convert from seconds to hours, minutes and seconds:
var hours = Math.floor(sec / 3600);
var minutes = Math.floor((sec - hours * 3600) / 60);
var seconds = Math.round(sec - hours * 3600 - minutes * 60);
Math with days, months and years should be somewhat similar but my rusty brain doesn't want to think about it
UPD
This function seems to do what you need
const daysFmt = days => {
const years = Math.floor(days / 365);
const months = Math.floor((days - years * 365) / 30);
const d = Math.round(days - years * 365 - months * 30);
let res = [];
if (years > 0) {
res.push(years + ' y');
}
if (months > 0) {
res.push(months + ' m');
}
if (d > 0) {
res.push(d + ' d');
}
return res.join(', ');
}
But this solution has one nuance: it assumes that month = 30 days. You might want to add if statement to return '1 m' if input is 31 or just return number of days if it is less than 32. Test results:
daysFmt(31);
"1 m, 1 d"
daysFmt(180);
"6 m"
daysFmt(185);
"6 m, 5 d"
daysFmt(356);
"11 m, 26 d"
daysFmt(365);
"1 y"
daysFmt(420);
"1 y, 1 m, 25 d"
daysFmt(3650);
"10 y"
daysFmt(3685);
"10 y, 1 m, 5 d"

How to calculate difference between two dates in hours? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
As I am new to javascript so I am asking this question how to find difference between two dates in hours.I am successfully calculated difference but when I give time in format of AM/PM it gives me output as NAN Please check my code I am posting below and thanks in advance:
function calculateTime() {
var d2 = new Date('2018-02-12 03:00:00 AM');
var d1 = new Date('2018-02-10 08:00:00 AM');
var seconds = (d2- d1)/1000;
var hours = seconds/3600;
console.log(hours);
}
calculateTime();
Simply subtract the date objects from one another.
var hours = Math.abs(date1 - date2) / 36e5;
The subtraction returns the difference between the two dates in milliseconds. 36e5 is short for 60*60*1000 and so dividing by 36e5 will give you hours.
Firefox will return Invalid date for the format YYYY-MM-DD HH:MM:SS AM
One option is to use year, month, day separately on new Date()
new Date(year, month [, day [, hours [, minutes [, seconds [,
milliseconds]]]]]);
Like:
function calculateTime() {
var formatDate = function(dt) {
let n = dt.split(/\D/).splice(0,6);
n[3] = dt.slice(-2) === 'PM' ? ( +n[3] + 12 ) : n[3]; //Update Hour
n[1] = n[1] - 1; //Update month
return n;
}
var d2 = new Date(...formatDate('2018-02-12 03:00:00 AM'));
var d1 = new Date(...formatDate('2018-02-10 08:00:00 AM'));
var seconds = (d2 - d1) / 1000;
var hours = seconds / 3600;
console.log(hours);
}
calculateTime();
Doc: new Date

Categories

Resources