Date calculation using javaScript - javascript

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

Related

Epoch to date UTC+3

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/

how to convert days to month in js?

This is my code:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var startDate = new Date( date1.split("/")[2], date1.split("/")[1]-1, date1.split("/")[0] );
var endDate = new Date( date2.split("/")[2], date2.split("/")[1]-1, date2.split("/")[0] );
var diff = new Date(endDate - startDate);
var diffResult = ((diff.getFullYear() - 1970) * 12+ diff.getMonth()) + " months";
so the output is only 35 months (and also 30 days but its hidden)
but as 30 days are actually already a month, I would like to have it as 36 months.
any suggestions?
thanks
There are several good thoughts/solutions in the comments. It seems what you're really after is the number of 30-day intervals that fit between the start and end date.
After all, 30 days is not always a month as months can have 31 days.
If you're interested in how many 30-day intervals fit between a start and end date you can count the days and divide by 30:
var date1 = '01/02/2017';
var date2 = '31/01/2020';
var dateRegex = /\d+/g;
var date1Array = date1.match(dateRegex);
var date2Array = date2.match(dateRegex);
var startDate = new Date(date1Array[2], date1Array[1], date1Array[0]);
var endDate = new Date(date2Array[2], date2Array[1], date2Array[0]);
var diffResult = Math.round((endDate-startDate)/(1000*60*60*24));
var months = Math.floor(diffResult/30);
alert(months);
Credit for the equation to get the number of days goes to this question.

Get the number of days between 2 dates using Javascript

actually the code works fine when the date is on the same month but i had a problem when the date is on the different month like 30/09/2015 and 01/10/2015 the number of days result is 2.(sorry for my bad english)
Here's the sample code:
var dtElem1 = '30/09/2015';
var dtElem2 = '01/10/2015';
var resultElem = frm.elements['numberofdays'];
var oneDay = 24*60*60*1000;
var x = dtElem1.value;
var y = dtElem2.value;
var arr1 = x.split('/');
var arr2 = y.split('/');
var dt1 = new Date();
dt1.setFullYear(arr1[2], arr1[1], arr1[0]);
var dt2 = new Date();
dt2.setFullYear(arr2[2], arr2[1], arr2[0]);
resultElem.value = Math.round(Math.abs((dt1.getTime() -
dt2.getTime())/(oneDay)));
The Date methods count months from zero, so you should substract 1 from the month number when setting the date. That explains your bug, since you end up substracting the 30th of october from the 1st of november and october has 31 days.
This will give the expected result:
dt1.setFullYear(arr1[2], arr1[1] - 1, arr1[0])
dt2.setFullYear(arr2[2], arr2[1] - 1, arr2[0])
Note that you don't need to create the Date and then set it. You can pass the same arguments directly to the constructor:
dt1 = new Date(arr1[2], arr1[1] - 1, arr1[0])
dt2 = new Date(arr2[2], arr2[1] - 1, arr2[0])

How to determine one year from now in Javascript

I'm trying to get one year from now's date, and it's not working.
JS:
var now = new Date();
var oneYr = new Date();
oneYr.setYear(now.getYear() + 1);
$("#yearFromNow").append(oneYr.toString());
var oneMonth = new Date();
oneMonth.setMonth(now.getMonth() + 1);
$("#monthFromNow").append(oneMonth.toString());
Output:
one mo. = Thu Dec 22 112 15:16:01 GMT-0500 (Eastern Standard Time)
one yr. = Sun Jan 22 2012 15:16:01 GMT-0500 (Eastern Standard Time)
The year has Dec 22 112 - ?? The month is correctly displaying Jan 22 2012.
If you want to tinker with it, http://jsbin.com/alezaj/edit#javascript,html,live. This is in Chrome and Firefox.
Thanks!
This will create a Date exactly one year in the future with just one line. First we get the fullYear from a new Date, increment it, set that as the year of a new Date. You might think we'd be done there, but if we stopped it would return a timestamp, not a Date object so we wrap the whole thing in a Date constructor.
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).
Thus a date marking exactly one year from the present moment would be:
var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);
Note that the date will be adjusted if you do that on February 29.
Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().
As setYear() is deprecated, correct variant is:
// plus 1 year
new Date().setFullYear(new Date().getFullYear() + 1)
// plus 1 month
new Date().setMonth(new Date().getMonth() + 1)
// plus 1 day
new Date().setDate(new Date().getDate() + 1)
All examples return Unix timestamp, if you want to get Date object - just wrap it with another new Date(...)
Use this:
var startDate = new Date();
startDate.setFullYear(startDate.getFullYear() - 1);
Using some of the answers on this page and here,
I came up with my own answer as none of these answers fully solved it for me.
Here is crux of it
var startDate = "27 Apr 2017";
var numOfYears = 1;
var expireDate = new Date(startDate);
expireDate.setFullYear(expireDate.getFullYear() + numOfYears);
expireDate.setDate(expireDate.getDate() -1);
And here a a JSFiddle that has a working example: https://jsfiddle.net/wavesailor/g9a6qqq5/
Use setFullyear as others have posted but be aware this returns a timestamp value not a date object. It is also a good candidate imho to add functionality via the prototype. This leads us to the following pattern:
Date.prototype.addYears = function(n) {
var now = new Date();
return new Date(now.setFullYear(now.getFullYear() + n));
};
console.log('Year from now is', new Date().addYears(1));
In very simple way. use this code.
// define function
function nextYearDate(date1) {
var date2 = new Date(date1);
var date3 = date2.setDate(date2.getDate() - 1);
var date = new Date(date3);
var day = date.getDate();
var month = date.getMonth()+1;
var year = date.getFullYear()+1;
var newdate = year + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
$("#next_date").val(newdate);
}
// call function.
<input type="date" name="current_date" id="current_date" value="" onblur="nextYearDate(this.value);" />
<input type="date" name="next_date" id="next_date" value="" onblur="nextYearDate(this.value);" />

Getting day of the week from timestamp using JavaScript

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();

Categories