difference between two dates based on set format - javascript

const formatChatDate = (chatDate) => {
// round to the nearest whole number
const dt = Moment(chatDate).format('MMMM Do YYYY, h:mm:ss a'); // March 9th 2021, 7:16:16 pm;
const dtNow = Moment(new Date()).format('MMMM Do YYYY, h:mm:ss a'); // March 9th 2021, 7:16:16 pm;
const diffDate= Math.round((dt-dtNow)/(1000*60*60*24));
if(diffDate.diff(dt,'days')<1){
return dt.format("LT");
}else{
return dt.format("LLL");
}
};
I need to calculate the difference between two dates and yesterday chat it will look like ll format and current date lt formate
I need to set 11.59pm mean ll format and 12pm mean lt format.. chatdate mean last message date and dtnow mean current date

Why don't use moment's diff to calculate difference between dates? Something like:
const formatChatDate = (chatDate) => {
const dt = moment(chatDate);
const dtNow = Moment(new Date());
if(dtNow.diff(dt,'days') < 1){
return dt.format("LT");
} else {
return dt.format("LLL");
}
};

const formatChatDate = (chatDate) => {
if(!chatDate) return '';
const dt = Moment(chatDate);
// dt.set({hour:0,minute:0,second:0,millisecond:0})
const dtNow = Moment(new Date());
if(dtNow.diff(dt, 'days') < 1) {
console.log(dt.format("LT"));
//console.log(dtNow);
return dt.format("LT");
// return chatDate;
} else {
return dt.format("LLL");
}
};
[![
march 8 2021 10.21 am and 11.12 pm same date but I got different format #Giovanni Esposito
][2]][2]

Related

How do I get the days between the today's day and the last day of the month using Moment.js?

Here's the code that I have right now:
const moment = require('moment')
const m = moment
const currDay = m().format('D')
const dayOfWeek = m().format('dddd')
const daysInMonth = m().daysInMonth()
const startOfMonth = moment().startOf('month').format('YYYY-MM-DD hh:mm');
const endOfMonth = moment().endOf('month').format('YYYY-MM-DD hh:mm');
I need to create a calendar row where the first item would be the todays date, and the rest of the calendar items would be the whatever amount of days are left depending on the current month so I could render each day in between in my HTML with Vue.
Example: Wed 8, Thu 9, Fri 10 ... Fri 31.
I think the OP is tripped up on the common mistake of formatting prematurely. format is good to see an intermediate result, but doing so produces a string that's no good for additional calculation.
Try to handle date objects only. Convert to strings only when you must: (a) presenting to a human reader, or (b) serializing for storage or transmission.
Working without formatting...
const daysRemainingThisMonth = moment().endOf('month').diff(moment(), 'days');
console.log(`There are ${daysRemainingThisMonth} days remaining this month`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
Just as a POJS equivalent, if you have a function to return the last day of the month, you can use that and just get the difference between the two dates, e.g.
function getMonthEnd(date = new Date()) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0);
}
function getMonthDaysLeft(date = new Date()) {
return getMonthEnd(date).getDate() - date.getDate();
}
let d = new Date();
console.log(`There are ${getMonthDaysLeft(d)} days left in ${d.toLocaleString('en',{month:'long'})}.`);
To get a list/array of the days remaining, just loop over a date, adding 1 day at a time, and write the dates in the required format into the list:
function getMonthDaysLeftAsList(date = new Date()) {
let d = new Date(+date);
// Formatter
let f = new Intl.DateTimeFormat('en',{
day: 'numeric',
month: 'short'
});
let m = d.getMonth();
let dayList = [];
while (d.getMonth() == m) {
dayList.push(f.format(d));
d.setDate(d.getDate() + 1);
}
return dayList;
}
console.log(getMonthDaysLeftAsList());

date-fns Format Date and Age calculation problem in React

I was using "moment.js" in my project (like age calculator), but I want to replace it with "date-fns".
Using moment.js, I formatted the input value as DD / MM / YYYY (for TR) and was calculating the age by subtracting the current date but right now I am having trouble doing this with date-fns. I felt like moment.js came easier to use.
Moment.js age calculator codes: I entered the input on 10/03/1998. (DD/MM/YYYY -> Turkey)
const birthDay = moment(value, 'DD/MM/YYYY');
console.log(birthDay); // (output: 10/03/1998)
const now = moment();
console.log(now); // (output: Thu Mar 04 2021 10:40:09 // TR Local Time)
const age = moment.duration(now.diff(birthDay)).years();
console.log(age); // (output: 22)
I tried to do it with date-fns but was not successful. I can not calculate the age.
const birthDay = format(new Date(value), 'dd/MM/yyyy');
console.log(birthDay); // (output: 03/10/1998 - **issue 1**)
const now = new Date();
console.log(now); // (output: Thu Mar 04 2021 10:45:18 // TR Local Time)
const age = differenceInCalendarYears(now, birthDay);
console.log(age); // (output: NaN - - **issue 2**)
I would appreciate it if you could help with date-fns.
I edited for the answer, right now it's like this:
const birthDay = new Date(value);
console.log(birthDay); // Oct 03 1998 (03/10/1998) it's MM/DD, I want DD/MM
const now = new Date();
console.log(now); // Mar 04 2021
const age = differenceInCalendarYears(now, birthDay);
console.log(age); // it should be 22 but 23.
Your age depends on whether you had your anniversary on the current year. That's why you should NOT use differenceInCalendarYears to calculate the age: it does not take into account the current month and day, only the year.
Use differenceInYears instead, or intervalToDuration if you want to get the age including months and days.
const { differenceInCalendarYears, differenceInYears, intervalToDuration, parse } = require("date-fns")
function calculateAge(dob) {
const date = parse(dob, "dd/MM/yyyy", new Date());
const age = differenceInYears(new Date(), date);
return age;
}
// INCORRECT
function calculateAge2(dob) {
const date = parse(dob, "dd/MM/yyyy", new Date());
const age = differenceInCalendarYears(new Date(), date);
return age;
}
console.log("dob = 01/04/2000"); // Running on 2021-08-05
console.log('- using differenceInYears: ', calculateAge("01/04/2000")); // 21
console.log('- using differenceInCalendarYears: ', calculateAge2("01/04/2000")); // 21
console.log("dob = 01/10/2000"); // Running on 2021-08-05
console.log('- using differenceInYears: ', calculateAge("01/10/2000")); // 20
console.log('- using differenceInCalendarYears: ', calculateAge2("01/10/2000")); // 21
function calculateFullAge(dob) {
const birthDate = parse(dob, "dd/MM/yyyy", new Date());
const { years, months, days } = intervalToDuration({ start: birthDate, end: new Date()});
return { years, months, days };
}
// Running on 2021-08-05
console.log('- using intervalToDuration: ', calculateFullAge("01/04/2000")); // {years: 21, months: 4, days: 4}
console.log('- using intervalToDuration: ', calculateFullAge("01/10/2000")); // {years: 20, months: 10, days: 4}
You can run this in the following runkit
I recently had a similar situation & this is how I implemented it
import { differenceInYears, parse } from "date-fns"
const calculateAge = (dob: string): number => {
const date = parse(dob, "dd/MM/yyyy", new Date())
const age = differenceInYears(new Date(), date)
return age
}
calculateAge("11/11/2019") // returns 2
PS: consider removing types (:string & :number) if you're only using JS
Try this ;)
import { intervalToDuration } from "date-fns"
const calculateAge = (dob: string): number => {
const interval = intervalToDuration({
start: new Date(dob),
end: new Date(),
})
return interval.years ? interval.years : 0
}
Your problem is parsing the date string (timestamp) using:
const birthDay = new Date(value);
It's strongly recommended not to use the built–in parser, see Why does Date.parse give incorrect results?
Since you're using Date.fns, use it for parsing too.
And as #volpato points out, you should use differenceInYears not differenceInCalendarYears as the later is effectively just currentDate.getFullYear() - birthday.getFullYear():
let dateFns = require("date-fns")
let d = '10/03/1998'; // 10 Mar 1998
let date = dateFns.parse(d, 'dd/MM/yyyy', new Date());
let age = dateFns.differenceInYears(new Date(), date);
console.log(age); // 23 when run on 4 Mar 2021
The above can be run at npm.runkit.com

Javascript date conversion and adding days

I have a date in the form of a string like below:
var dateInput= "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
I want to convert this date to dd/mm/yyyy and be able to add and subtract days from this date and still retain the same format.
Here's what I did to convert this string to dd/mm/yyyy date format:
I used this helper function:
function convertDate(inputFormat) {
function pad(s) { return (s < 10) ? '0' + s : s; }
var d = new Date(inputFormat);
return [pad(d.getDate()), pad(d.getMonth()+1), d.getFullYear()].join('/');
}
So, then I did :
var date = new Date(convertDate(eddFromCouch));
which gave me the string 7/12/2019;
Then, when I tried to add the 5 days to the date above, I got the following:
date = date.setDate(date.getDate() + 5);
console.log(date); // returns 1563310800000
I believe 1563310800000 a UNIX timestamp which converts to July,16,2019
I was expecting it to return 12/12/2019.
Here is how you can achieve this using Moment.js. This library makes tasks like parsing, manipulating and displaying dates much easier to achieve.
var input = "2019-08-14T08:06:49.288Z";
var date = moment(input);
date.add(5, "days");
console.log(date.format("DD/MM/YYYY"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Your dateInput is actually the format returned by date.toString, and can be passed directly to the date constructor to get a date object.
function toDDMMYYY(date) {
let parts = [];
let dd = date.getDate();
let mm = date.getMonth() + 1;
let yyyy = date.getFullYear();
if (dd < 10) {
parts.push(`0${dd}`)
} else {
parts.push(`${dd}`)
}
if (mm < 10) {
parts.push(`0${mm}`)
} else {
parts.push(`${mm}`)
}
parts.push(yyyy)
return parts.join('/');
}
const input = "Sat Dec 7 2019 00:00:00 GMT+0300 (East Africa Time)";
let date = new Date(input);
date = new Date(date.setDate(date.getDate() + 5));
console.log(toDDMMYYY(date))

JavaScript Moment.js trying to get the difference between 2 datetimes

I am trying to get the difference between 2 datetimestamps which look like These:
2018-08-22 00:00:00
2018-08-11 15:34:31
I want to Show the difference in time in days - Hours - minutes - seconds left.
So far I did this but it Always return NaN:
import moment from 'moment';
const calc = {
render () {
moment().format();
this.calcDifference();
},
calcDifference() {
let releaseDate = document.getElementById('release-at').value;
let currentDate = document.getElementById('current-date').value;
let ms = moment(
releaseDate,
"DD-MM-YYYY HH:mm:ss").diff(moment(currentDate,
"DD-MM-YYYY HH:mm:ss")
);
let d = moment.duration(ms);
let s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");
console.log(ms);
console.log(d);
console.log(s);
}
};
calc.render();
on your calcDifference function, you can do something like this
let releaseDate = moment('2018-09-22 00:00:00');
let currentDate = moment('2018-08-11 15:34:31');
const diff = releaseDate.diff(currentDate);
const diffDuration = moment.duration(diff);
console.log(`
${diffDuration.months()} months
${diffDuration.days()} days
${diffDuration.hours()} hours
${diffDuration.minutes()} minutes
${diffDuration.seconds()} seconds left!`);
in case values from release-at and current-date elements have format
DD-MM-YYYY HH:mm:ss, use
let releaseDate = moment(document.getElementById('release-at').value, 'DD-MM-YYYY HH:mm:ss');
let currentDate = moment(document.getElementById('current-date').value, 'DD-MM-YYYY HH:mm:ss');
Here's a working codepen
I hope it helps! :)

How to compare dates in Javascript without using year?

The title says it all. I'm using MomentJS in other areas, so I am comfortable with a solution that uses moment (or not - either way is fine). In this solution, the function would return the shortest path to the compared date. e.g. comparing 12-31 to 01-01 would return 1, not 364. Basically this is what I am looking to do:
var today = '08-06'; // august 6th
var dateOne = '09-03' // september 3rd
var dateTwo = '02-29' // february 29th
var dateThree = '01-01' // january 1st
getDifferenceInDays(today, dateOne); // => 28
getDifferenceInDays(today, dateTwo); // => -159
getDifferenceInDays(today, dateThree); // => 147
This works with MomentJS. The caveat is that when you initialize MomentJS date it implicitly adds the year to this year. So, the assumption is that these values are calculated for this year
function getDifferenceInDays(date1, date2) {
var day1 = moment(date1,'MM-DD').dayOfYear();
var day2 = moment(date2,'MM-DD').dayOfYear();
var diff1=(day2 - day1)
var diff2=365- Math.abs(diff1)
if (Math.abs(diff1)>Math.abs(diff2)) {
return diff2;
} else {
return diff1;
}
}
var today = '08-06'; // august 6th
var dateOne = '09-03' // september 3rd
var dateTwo = '02-29' // february 29th
var dateThree = '01-01' // january 1st
console.log(";;;;")
console.log(getDifferenceInDays(today, dateOne)); // => 28
console.log(getDifferenceInDays(today, dateTwo)); // => -159
console.log(getDifferenceInDays(today, dateThree)); // => 147
http://jsfiddle.net/r2brgf4r/
You should be able to do this pretty easily with MomentJS by getting the month and day of the month from your Date object.
var getDifferenceInDays = function(date1, date2) {
var day1 = date1.dayOfYear();
var day2 = date2.dayOfYear();
if (Math.abs(day1 - day2) < (365 - Math.abs(day2 - day1))) {
return Math.abs(day1 - day2);
} else {
return (365 - Math.abs(day1 - day2));
}
}
Moment's "dayOfYear()" function returns the day of the year (a number between 1 and 366). Hope this helps!

Categories