So while I use the following code to check if the difference between 2 dates is X days
var selectedDate = moment(value, 'MM/DD/YYYY');
var today = moment();
today.diff(selectedDate, 'days');
I want to check if the difference between the selected date and the current dates is beyond X month (e.g. say 14 months), then I want to alert some error.
Is there an easy way to do that using moment.js ? I want that leap years and all are also considered automatically.
You can use today.diff(selectedDate, 'months');.
Documentation
var selectedDate = moment("2020-04-21").format('YYYYMMDD');
var newdDate = moment("2020-01-22").format('YYYYMMDD');
var today = moment();
var difference = today.diff(selectedDate, 'months');
console.log('Difference', difference);
var diff = today.diff(newdDate, 'months');
console.log('New Date Difference', diff);
var floatingDiff = today.diff(selectedDate, 'months', true);
console.log('Floating', floatingDiff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
You can use moment().diff() to calculated diff b/w today & selected date or pass new date to moment if you want difference between any other date.
import moment from "moment";
const selectedDate = "2020-04-27";
const date_temp = moment().diff(selectedDate, 'months');
console.log(date_temp);
Related
I used this code to convert epoch to human readable date
var timestamp = 1293683278;
var date = new Date(timestamp*1000);
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
I need to change it to UTC+3 how can i do this ?
Thanks for your help
The Date constructor treats time values as UTC. Date objects only ever represent UTC time, the "local" values produced by toString methods use system settings to determine the offset to use, but that's only for the sake of producing a timestamp, it doesn't change the underlying Date or its time value.
If you want a specific offset, you can choose an appropriate IANA location such as Africa/Nairobi, which is +3 all year round, and produce a timestamp using toLocaleString or Intl.DateTimeFormat, e.g.
console.log(
new Date().toLocaleString('default',{timeZone:'Africa/Nairobi', timeZoneName:'short'})
);
Just curious - but couldn't you just append 3 hours onto your timestamp before formatting it with your existing code. I'm curious if there's some date/calendar subtlety where this wouldn't reliably work.
const THREE_HOURS_IN_MS = 3*60*60*1000;
var date = new Date(timestamp*1000 + THREE_HOURS_IN_MS);
// rest of your code stays unchanged
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
You can use moment.js utcOffset to achieve this easily:
const moment = require("moment");
const timestamp = 1619071948 * 1000;
console.log(moment(timestamp).utcOffset(180).format("YYYY-MM-DDThh:mm:ssZ"));
The offset provided is in minutes
https://momentjs.com/docs/#/manipulating/utc-offset/
I need date algorithms, Which will display me how long I have been given a date anywhere.
Example:
Suppose
Today is 01/06/2019 (dd/mm/yy)
BirthDate is 31/05/2019 (dd/mm/yy)
Now, My age is 1 day 0 Months and 0 years
[NOTE: I need all of them, It means day/month and years]
I have been read at least 23 articles/post in this site but they only give years or month or date but not everything in one...
var date, cDate, cMonth, cYears, oDate, oMonth, oYears;
date = new Date()
//current date
cDate = date.getDate()
cMonth = date.getMonth()
cYears = date.getFullYear()
//birth date
oDate = 01
oMonth = 05
oYears = 2019
(Multiplying is not the main solution I think so, need to work with all arithmetics operator)
This will give you the result you need
var birth = new Date("5/31/2019"); // mm/dd/year
var today = new Date();
var diff = today.valueOf()-birth.valueOf();
var result = new Date(diff);
var dayDiff = result.getDate() - 1; //because epoch start from 1st
var yearDiff = result.getFullYear() - 1970; //because epoch start from 1970
var str = `${dayDiff} day ${result.getMonth()} Months and ${yearDiff} years`;
console.log(str);
You should use moment, so there you can do:
var a = moment("04/09/2019 15:00:00");
var b = moment("04/09/2013 14:20:30");
console.log(a.diff(b, 'years'))
console.log(a.diff(b, 'months'))
console.log(a.diff(b, 'days'))
Similarly, you can get minutes, hours and seconds if you need.
While using the library moment.js
How do I get the time difference between two different dates variables, specifically in years, months and days using moment.js?
I found this method but I keep getting weird results. Sometimes the result is one month ahead so I added a subtract one months part to make the result correct, but when the difference between the two dates can be divided into whole years it then becomes a month behind, but then if I remove the subtract month part, it gets even more out of whack.
Also I would like to format it as "X Years, Y Months, Z days", but also can't figure out how to format it in such way.
var dateOne = new Date(2000,07,16);
var dateTwo = new Date (1990,07,16);
var updatedDate = moment(dateOne).format('ll');
var x = moment(dateOne, 'DD/MM/YYYY').diff(moment(dateTwo, 'DD/MM/YYYY'))
var y = moment.duration(x);
var why = moment(x).subtract(1, 'M');
var z = Math.floor(y.asYears()) + moment.utc(why).format('/MM/DD');
console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Try this perhaps?
var firstDate = moment();
var secondDate = moment("2018-03-19");
var yearDiff = firstDate.diff(secondDate, "year");
var monthDiff = firstDate.diff(secondDate, "month");
var dayDiff = firstDate.diff(secondDate, "day");
console.log(yearDiff + " Years, " + monthDiff + " Months, " + dayDiff + " Days");
https://jsfiddle.net/px1brLdk/
As stated by others in the comments, you can't format a duration as a date and since dateOne and dateTwo are a Date objects, there is no need for the second argument in moment(dateOne, 'DD/MM/YYYY'), simply use moment(Date).
Moverover, please note that when you use new Date(year, monthIndex, day) monthIndex starts from 0, see MDN docs:
The argument monthIndex is 0-based. This means that January = 0 and December = 11.
You can use moment-duration-format plug-in to format momentjs duration according your needs, see format() docs on the plug-in page.
Here a live sample:
var dateOne = new Date(2000, 7, 16);
var dateTwo = new Date(1990, 7, 16);
var diff = moment(dateOne).diff(moment(dateTwo))
var dur = moment.duration(diff);
var result = dur.format();
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
Moment is having a method called .diff() Use that one.
https://momentjs.com/docs/#/displaying/difference/
$.each(data[i].replies, function(m, n) {
var currentdate = new Date();
console.log(n.entry.date_entered);
check = moment(n.entry.date_entered, 'YYYY/MM/DD');
check1 = moment(currentdate, 'YYYY/MM/DD');
console.log(check);
console.log(check1);
var month = check.format('M');
var day = check.format('DD');
var year = check.format('YYYY');
var month1 = check1.format('M');
var day1 = check1.format('DD');
var year1 = check1.format('YYYY');
get = moment([year, month, day]);
get1 = moment([year1, month1, day1]);
g = get1.from(get);
});
Sample n.entry.date_entered : 2014-07-28 12:23:43
For all the dates i am getting a few seconds ago don't know why
I think your problem is the format mask that you pass in to moment.
In your sample you use - as the delimiter but in your format mask you use /. This way moment will not be able to parse the date and will give you the current date instead.
Try changing your format mask to "YYYY-MM-DD".
How do I get the day of the week from a timestamp in JavaScript?
I'd like to get this from a timestamp I specify, not the current date.
Thanks
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var dayOfWeek = days[a.getDay()]
Now the "day of the week" is in the dayOfWeek variable.
var timestamp = 654524560; // UNIX timestamp in seconds
var xx = new Date();
xx.setTime(timestamp*1000); // javascript timestamps are in milliseconds
document.write(xx.toUTCString());
document.write(xx.getDay()); // the Day
2020 Update
If this browser support is acceptable for you you can use this one liner:
new Date(<TIMESTAMP>).toLocaleDateString('en-US', { weekday: 'long' }); // e.g. Tuesday
Similar to klidifia's answer, but for some reason the day of the week was off. I had to update the 'days' array to start on Monday.
var timestamp = 1400000000;
var a = new Date(timestamp*1000);
var days = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday', 'Sunday'];
var dayOfWeek = days[a.getDay()]
Try out the following:
var currentTime = new Date();
var day = currentTime.getDate();