creating a countdown with Moment.js, the days are off [duplicate] - javascript

This question already has answers here:
How to get difference between 2 Dates in Years, Months and days using moment.js
(3 answers)
Closed 12 days ago.
I am currently creating a countdown for a website that will display the months/days/hours/minutes untill a set date.
It looks fine, as it displays: 1 MONTHS 5 DAYS 15 HOURS.
But I tried to calculate it by hand and it should be 1 month, and 9 days. So i am missing a couple of days in the calculation.
I've tried multiple setups and even converted the datetime to ISO 8601 but to no avail. They all display the same months/days.
I'm sure it's something small I am overlooking, but I can't find it.
The end date should be 16th of March 2023.
I have copied and cleaned the code from the project and placed it in a codepen (look in the console for the output).
let date = moment('2023-03-16T08:30:00+0100');
var dur = moment.duration( moment(date).diff(moment()) );
let yearsRemain = dur.years();
let monthsRemain = dur.months();
let daysRemain = dur.days();
let hoursRemain = dur.hours();
let minutesRemain = dur.minutes();
let secondsRemain = dur.seconds();
var dateArray = [
yearsRemain,
monthsRemain,
daysRemain,
hoursRemain,
minutesRemain,
secondsRemain
]
console.table(dateArray);
https://codepen.io/Skippy/pen/ExpJrmm
What am I doing wrong?

Instead of moment.js you can use Countdown.js please refer to the included snippet and check if it yields the expected result:
let date = new Date('2023-03-16T08:30:00+0100');
let cd = countdown(date).toString()
$(".test").append(cd);
.test{
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/countdown/2.6.0/countdown.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test"></div>

Related

Javascript: check if timestamp is 24hrs old or less [duplicate]

This question already has answers here:
Calculating the difference between two dates
(10 answers)
Check if a date is 24 hours old
(5 answers)
What's the best way to calculate date difference in Javascript
(2 answers)
Closed 2 years ago.
I need to fetch bitbucket repositories and filter them according to the updated_on timestamp.
GOAL: Is to filter the ones which are updated in last 24 hours.
This is what I get from API : updated_on: 2018-01-30T11:45:32.902996+00:00
My code logic:
// repo's updated_on timestamp (example)
const time = '2018-01-30T11:45:32.902996+00:00'
let currentTime = Date.now()
let updatedOn = new Date(time).getTime()
const filter = () => {
// boolean
return (currentTime - updatedOn) > 86400000)
}
if (filter()) {
// NOT FILTERING // giving out last month's data as well
console.log(updatedOn)
}
Ciao, with moment library you could use isBefore function in this way:
let date = "2018-01-30T11:45:32.902996+00:00";
let anotherDate = moment(); // today
console.log(moment().subtract(24, 'hours').isBefore(moment(new Date(date))));
console.log(moment().subtract(24, 'hours').isBefore(moment(new Date(anotherDate))));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Convert the difference between 2 dates to 'y mo d' format using Moment.js

I am running into a wall trying to figure out how to convert the difference between two dates to an accurate breakdown of how many years, months and days it's been since the start date.
The format I want to show is: '1y 5mo 2d' given two dateTimes that have that difference.
I tried using Moment.js and it works pretty well for 'y' and 'mo' but I am running into a wall trying to figure out how to accurately get the number of days.
export const convertDaysToYMD = (dates: {start, end})=>{
const start = Moment(dates.start)
const end = Moment(dates.end)
const y = end.diff(start, 'years')
const m = end.diff(start, 'months')
const d = end.diff(start, 'days')
console.log('y', y + ' m', m%12 + ' d', d)
}
I can accuratly get the number of years and then the number of months by using mod(12) but due to the number of days changing per month I don't quite know how to get the number of days. Any help would be great.
You can use moment's duration method like this:
const start = moment('2020-01-02');
const end = moment('2020-02-03');
const duration = moment.duration(end.diff(start));
console.log(`${duration.years()} years ${duration.months()} months and ${duration.days()} days.`)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

moment - Issue with fromNow

Hey I'm trying to calculate user age using Moment.
function getAge(birthDate) {
const start = moment(birthDate, "YYYY-MM-DD");
const end = moment();
return start.to(end, true);
}
Before the month of may, the result is 1 year over:
getAge("1989-01-01"); // 31 years
getAge("1989-05-01"); // 30 years
example: https://codesandbox.io/s/nostalgic-tesla-bzb3d
the behavior is the same using fromNow instead of to
do you have any idea on how to solve this?
The result of .to() is a relative time string and it internally rounds the values in either direction (so 29.5 years would become 30 years). It is meant for display purposes like showing "posted 3 minutes ago" in forum or blog posts.
You are looking for the .diff() method that calculates the difference, but will only account for full units of measurement provided by the second argument, i.e. truncating the actual number.
const start = moment(birthDate, "YYYY-MM-DD");
age = moment().diff(start, "years");
https://codesandbox.io/s/naughty-lewin-e6vrt
You may use diff function like:
function getAge(birthDate) {
const start = moment(birthDate, "YYYY-MM-DD");
const end = moment();
return end.diff(start, 'years');
}
console.log(getAge("1989-01-01"));
console.log(getAge("1989-05-01"));

How to find time difference between current date and another date [duplicate]

This question already has answers here:
Get hours difference between two dates in Moment Js
(17 answers)
Closed 3 years ago.
I'm searching a way to find the time difference between 2 dates using moment js in seconds only.
I want to compare current date with dates that I'm reading from the database.
For example:
//current time
var current_time= moment().format('YYYY-MM-DD HH:mm:ss');
//date from sql query
var starting_date=moment(element.start_date).format('YYYY-MM-DD HH:mm:ss');
// print the dates as they are now
console.log(current_time);
console.log(starting_date);
result:
2019-07-02 18:00:11
2019-05-03 15:59:29
I want to find the difference between these 2 dates in seconds only.
I try to make it work using something like this example i found:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days')
but it doesn't worked...
var current_time= moment().format('YYYY-MM-DD HH:mm:ss');
var starting_date=moment(element.start_date).format('YYYY-MM-DD HH:mm:ss');
current_time.diff(starting_date, 'seconds');
it crashes
Any idea how to achieve this?
You can use a.unix() - b.unix()
a.diff(b) will return diff in millisecond, you can div for 1000 to get second.
var a = moment('2019-07-02 18:00:11', 'YYYY-MM-DD HH:mm:ss');
var b = moment('2019-05-03 15:59:29', 'YYYY-MM-DD HH:mm:ss');
second = a.unix() - b.unix();
console.log('diff with second:' + second);
secondbymin = a.diff(b);
console.log('diff with milisecond: ' + secondbymin);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Display date with sum of weeks in jquery [duplicate]

This question already has answers here:
How to add number of weeks to the current date using JavaScript?
(5 answers)
Closed 5 years ago.
1- I have a number of weeks from an input field:
$("#numberWeek").on("keyup", function(){
var numberWeek = $(this).val();
console.log(numberWeek);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numberWeek" />
2- I have the number of the current week:
var todayDate = new Date();
var currentWeek = (0 | todayDate.getDate() / 7) + 1;
console.log(currentWeek);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
3- How can I display the date that we will find when we start to count from the current week (currentWeek) to the number of weeks that is in the variable numberWeek in this format : 26/07/2018 ?
Thanks in advance for any help.
You can use the moment.js (here documentation) library to achieve this easily, just use add method and pass as parameter week, something like this:
moment(todayDate).add(numberWeek, 'weeks').calendar()
here the idea working: https://jsbin.com/rokiluxosi/1/edit?html,js,output

Categories

Resources