currentDate.diff() is not a function error in moment.js - javascript

const currentDate = moment(new Date()).format('DD/MM/YYYY'); //03/01/2022
var days_diff = currentDate.diff(returnDate,'days'); // returnDate = 08/12/2021
console.log(days_diff)
Error:
Uncaught TypeError: currentDate.diff is not a function
I am trying to get the days difference between the current date and the return date but it is giving me an error currentDate.diff is not a function
Please solve this error.

This is because .format('DD/MM/YYYY') outputs a string, which is not going to have the Moment functions available to it. Instead do this:
const currentDate = moment(new Date('03/01/2022'));
const returnDate = moment(new Date('08/12/2021'));
var days_diff = currentDate.diff(returnDate,'days');
console.log(days_diff)
Maintain the Moment Date object throughout your operations. Formatting it early just makes it a string.

Related

Comparing two times in MomentJS in the format HH:mm?

Here I need to compare two times and have to check whether the current time is sameOrBefore the given time.
var workingDayTime = '1900'
var currentTime = moment().format("HH:mm")
var endTime = moment(workingDayTime,"HHmm").format("HH:mm")
console.log(currentTime) // 08:21
console.log(endTime) // 19:00
Assume the value of workingDayTime is coming from API in the format of ``HHMM`. I have checked the moment docs. And used something like endTime.isSameOrAfter(currentTime).
But it is returning endTime.isSameOrAfter is not a function . I believe this is because the current time and endTime have formatted to string this is not a function anymore. Is there any way to achieve the functionality I am looking for. Please help me with your suggestion and feedback
Compare the moment objects without the string formatting:
const workingDayTime = '1900'
const currentMoment = moment()
const currentTime = currentMoment.format('HH:mm')
const endMoment = moment(workingDayTime,"HHmm")
const endTime = endMoment.format("HH:mm")
const msg = (endMoment.isSameOrAfter(currentMoment))
? 'after'
: 'before'
console.log(`${endTime} is ${msg} ${currentTime}`)
Don't format dates before you compare them
import moment from "moment";
var workingDayTime = '1900'
var currentTime = moment()
var endTime = moment(workingDayTime,"HHmm")
console.log(endTime.isSameOrAfter(currentTime)) // true

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

How to convert dates to UNIX timestamps in MomentJS?

I want to convert my date time values to Unix timestamp format (basically an epoch timestamp). For that I use:
let startDate = '2018-09-28 11:20:55';
let endDate = '2018-10-28 11:20:55';
let test1 = startDate.unix();
let test2 = endDate.unix();
However it gives me an error
ERROR TypeError: Cannot read property 'Unix' of undefined
Can anyone tell me how I can convert datetime to Unix using MomentJS?
The issue is because you're calling unix() on plain strings. You need to instead call it on MomentJS objects. To create those, you can provide the date strings to a MomentJS constructor, like this:
let startDate = '2018-09-28 11:20:55';
let endDate = '2018-10-28 11:20:55';
let test1 = moment(startDate).unix();
let test2 = moment(endDate).unix();
console.log(test1);
console.log(test2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js"></script>

Javascript date undefined error

this is my code and I'm getting "Uncaught TypeError: undefined is not a function" what am i doing wrong?
var myDate = new Date().setDate(17);
document.getElementById("result").innerHTML = myDate.getDate();
setDate modifies the object it is called on and returns undefined. If you want to make somethingelse refer to the date that today referred to, but changing the day, you could copy today and then change somethingelse:
var today = new Date();
var somethingelse = new Date(today.getTime());
somethingelse.setDate(17);
document.getElementById("result").innerHTML = somethingelse.getDate();
Of course, if you didn’t care about preserving what was in today, you could certainly modify that without creating a copy.
var date = new Date();
date.setDate(17);
document.getElementById("result").innerHTML = date.getDate();
This much is enough: You can take the same today object and set and get date for that object.
var today = new Date();
today.setDate(17);
document.getElementById("result").innerHTML = today.getDate();
Fiddle

How to get time difference between two date time in javascript?

I want time duration between two date time. I have the start date, start time, end date and end time. Now I have to find the difference between them.
Actually I have tried with this following code, but I got the alert like 'invalidate date'.
function myfunction()
{
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var new_st_dt=new Date(start_dt);
var new_end_dt=new Date(end_dt);
alert('new_st_dt:'+new_st_dt);
alert('new_end_dt:'+new_end_dt);
var duration=new_end_dt - new_st_dt;
alert('duration:'+duration);
}
the alert msg like as follows:
new_st_dt:invalid date
new_end_dt: invalid date
duration:NaN
when I run in android simulator I got these alert messages.
Please help me how to get it? How to implement this?
You're passing an invalid ISO date string to that Date() constructor. It needs a form like
YYYY-MM-DDThh:mm:ss
for instance
2013-10-29T10:10:00
So you basically forgot the T to separate date and time. But even if the browser reads in the ISO string now, you would not have an unix timestamp to calculate with. You either can call
Date.parse( '2013-10-29T10:10:00' ); // returns a timestamp
or you need to explicitly parse the Date object, like
var duration=(+new_end_dt) - (+new_st_dt);
Further read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Try formatting you timestamps as isoformat so javascript recognizes them. (you put a "T" between the date and time). An example: '2013-10-29T10:10:00'
function dateDiff(){
var start_dt = '2013-10-29 10:10:00';
var end_dt = '2013-10-30 10:10:00';
var d1= start_dt ;
d1.split("-");
var d2= end_dt ;
d2.split("-");
var t1 = new Date(d2[0],d2[1],d2[2]);
var t2 = new Date(d1[0],d1[1],d1[2]);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
return Math.abs(Seconds_from_T1_to_T2);
}

Categories

Resources