Days between dates in DayJS UK Format - javascript

Im using dayjs, and I'm trying to calculate the days between 2 days so that I can output Today, Tomorrow and X days time
The problem I'm having though seems to be with the date formats
const date1 = dayjs('31/10/2021');
const date2 = dayjs().format("DD/MM/YYYY")
let hours = date2.diff(date1, 'days')
No matter how I try, I'm getting date2.diff is not a function when I add .format to date2. Does anyone know how to format this correctly and get the correct outcome?
If i try const date1 = dayjs('31/10/2021').format("DD/MM/YYYY"); then it errors with invalid date

You can try the following:
const date1 = dayjs('2021-01-25');
const date2 = '01/11/2020'; // or '2020-11-01'
let hours = date1.diff(date2, 'day')
console.log(hours) // 380
The format function just returns a string. This is why date2.diff is not a function.
The diff function is only available for dayjs objects (not for strings).
Docs for difference function: https://day.js.org/docs/en/display/difference
Docs for format function: https://day.js.org/docs/en/display/format

const date1 = dayjs('2019-01-25')
date1.diff('2018-06-05', 'day', true)
You don't need to call format function, just use dayjs constructor to convert both dates to dayjs object and return the difference between the 2 dates in number of days.

Related

How to increase the day in this date string '2022-05-06' in JS

How to increase the day in this date string '2022-05-06' in JS? It can be both native and moments solution. I checked add method in moment but looks like I am doing something wrong and it doesn't work:
const date = '2022-05-06'
console.log(moment(date).add(1, 'days'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.3/moment.min.js"></script>
You should parse string to moment object properly:
const date = '2022-05-06'
const newDate = moment(date,'YYYY-MM-DD').add(1, 'days');

How to check if date is a current date with using dayjs?

I have a problem with checking if my date in unix is a current date with using dayjs library, I try like below:
const date = 1631978008; //today: 2021-09-18
const isToday = dayjs().isSame(date, 'day'); //return false
but always return me false when my date is a today date, can someone tell me why? it should return true :/
thanks for any help!
You can use the unix function to parse the unix timestamp in seconds before comparing it with the current time.
const date = 1631978008; //today: 2021-09-18
const isToday = dayjs().isSame(dayjs.unix(date), 'day');
console.log(isToday);
<script src="https://unpkg.com/dayjs#1.8.21/dayjs.min.js"></script>

Getting 'NaN' while trying to convert a string of date to milliseconds [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 2 years ago.
Tried this:
1.
const today = new Date('28.08.2020');
const milliseconds = today.getTime();
const today = Date.parse("28.08.2020")
var today = new Date('28.08.2020');
var milliseconds = today.getMilliseconds();
Getting NaN while trying to convert a string of date to milliseconds
Better to change date format to YYYY-MM-DD as suggested in other answer
Or you can do something like this
var from = '28.08.2020'.split(".");
var today = new Date(from[2], from[1] - 1, from[0]);
const milliseconds = today.getTime();
console.log(milliseconds);
You use the incorrect format. If you get the date from backend you should convert it.
const date = '28.08.2020';
const [day, month, year] = date.split('.');
const validDate = new Date();
validDate.setFullYear(year);
validDate.setDate(day);
validDate.setMonth(month);
// or just
const validDate2 = new Date(year, month, day);
const milliseconds = validDate.getTime();
const milliseconds2 = validDate2.getTime();
console.log(milliseconds)
console.log(milliseconds2)
After this conversion you can use the date as you want
Assuming that you do not want to manually parse the string, you could try to use moment library, which allows one to provide custom dateString patterns used for parsing the date, like demonstrated below
const dateString = '28.08.2020';
const date = moment(dateString, "DD.MM.YYYY");
console.log("date", date); // displayed zulu time might be different than your local timezone
console.log("milliseconds", date.valueOf());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
Please take a note that moment will accept the date in your local timezone, which may pose some issues. If you want to make up for it, you should look up moment-timezone library
Oh, in that case you can change the imput to the "yyyy-mm-dd", is that a posibility?
const date = '28.08.2020';
let dateFromat = date.split('.');
dateFromat = `${dateFromat[2]}-${dateFromat[1]}-${dateFromat[0]}`;
const today = new Date(dateFromat);
const milliseconds = today.getTime();
output: 1598572800000
the dating format is wrong.
new Date('2020-08-28') should work

Moment JS days difference issue

I'm calculating the days difference between two dates using moment.js, but seems it wasn't calculated correctly.
const moment1 = moment(new Date('2020-04-05'));
const moment2 = moment(new Date('2020-01-06'));
const diff = moment1.diff(moment2 , 'days');
console.log(diff);
The output is 89 whereas the actual value should be 90. Specifically, if I change moment1 to '2020-04-04', the output is still 89. But after '2020-04-05' the value is always 1 day less than the actual value. Why?
You can simply pass dates you are checking for difference instead of using new Date() There is not requirement to use new Date() at all
Simple pass the date as string to moment and you will have 90 days.
Here is what moment.js diff says.
Run snippet below.
const moment1 = moment('2020-04-05');
const moment2 = moment('2020-01-06');
const diff = moment1.diff(moment2 , 'days')
console.log(diff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>

how to format date YYYYMMDDmmhhssuuu

I have a 'timestamp' value 20200513134950000 and the format should be YYYYMMDDmmhhssuuu.
I can not wrap my head around how to properly format it. I have tried date-fns library and native Date format, but with no luck.
Any ideas?
You can extract all the relevant parts from the number with a simple regexp or even by counting numbers. Then the only caveat is that months are zero-based, but apart from that, you can just use the standard Date() constructor.
const timestamp = 20200513134950000;
const UTC_mask = /(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{3})/;
const [
year,
month,
day,
hour,
min,
sec,
ms
] = timestamp.toString().match( UTC_mask ).slice( 1 );
const datetime = new Date( year, parseInt( month, 10 ) - 1, day, hour, min, sec, ms );
console.log( datetime );
Without any library you can just get the parts and pass them to the Date constructor:
let ts = '20200513134950000';
let [c,y,m,d,H,M,S] = ts.match(/\d\d/g);
console.log(new Date(c+y,--m,d,H,M,S).toString());
You can try using DayJS.
Its a lightweight library and allows you to specify custom parse format for parsing the dates.
const dayjs = require('dayjs');
var customParseFormat = require('dayjs/plugin/customParseFormat')
dayjs.extend(customParseFormat)
console.log(dayjs('20200513134950000', 'YYYYMMDDmmhhssuuu'))

Categories

Resources