JavaScript Calculate what exact date it would be after exactly X Years - javascript

Javascript- How to get an exact date after exactly 'X' years from a given date (birth date), say 'YYYY/MM/DD'

If you want to calculate age from date, here is the code you need:
var birthDate = getDateFromTextbox();
var today = new Date();
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
If you want calculate year from 2 dates, replace
var today = new Date();
by
var today = yourDate();
If you want add year to Date try it:
date.setYear(date.getFullYear + 7);

A trivial version would be
function addYearsToDate(date, years) {
return +date.slice(0, 4)+years + date.slice(4);
}
Here, the +date.slice(0,4) makes a number out of the first four characters of the date, to which we add the number of years, then concatenate that with the remainder of the input date.
> addYearsToDate('1953/04/18', 62)
< "2015/04/18"
You will need to special-case Feb. 29.
This assumes you want the input and output in string form YYYY/MM/DD. For more sophisticated date manipulation, consider using a library like moment which would allow you to do things like
moment('1953/04/18').add(62, 'years')

Related

Get all specific day in specific end date in JavaScript

I am trying to get all day (input by me) in a specific end date (input by me).
example :
I have day 1 and I have end date 10/12/2021
beginning from new Date():
output must be: 1/10/2021 1/11/2021 1/12/2021
day 1 for this month is not included because we are in day 20 and day 20 > day 1
Same, I chose day 20 (example) and end date = 19/12/2021 day 20 in end date not included because day 20 > end date day
I have already tried that as simple using if condition, but not great work because in this case, I have 8 conditions!
I want a simple code that works for this situation.
Hope that is what you wanted. You can simplify it more if you want.
const getRemainingDates = function(beginningDay, endDate){
const today = new Date()
const [endDateDay,endDateMonth,endDateYear] = endDate.split("/");
const remainingMonth = endDateMonth - (today.getMonth()+1);
for(let i = 0; i <= remainingMonth; i++){
if(i === 0){
if(beginningDay>today.getDate() && beginningDay>endDateDay){
console.log(`${beginningDay}/${today.getMonth()+1+i}/${today.getFullYear()}`)
}
else {}
}
if(i !== 0)console.log(`${beginningDay}/${today.getMonth()+1+i}/${today.getFullYear()}`)
}
}
getRemainingDates(21,"12/12/2021");
console.log()
getRemainingDates(1,"12/12/2021");

Validating credit card expiry date against todays date in JavaScript

I'm working on an assignment for school where we're working with JavaScript (I'm only allowed to use JavaScript) to validate a form for a payment page. It's my first time working with JavaScript so and I feel a bit lost...
I'm faced with a task to validate the expiry date and the requirements are:
the number needs to be exactly 2-2 digits (in the format mm-yy)
mm needs to be >01 and <12
and the expiry date needs to be after today's date
So far I've only been able to specify the first two requirements and I have trouble figuring out how to check the date against today's date.
html
<form>
<label for="expiryDate">Expiry Date</label>
<input type="text" name="expiryDate" id="expiryDate" />
<input type="submit" value="Check out" />
</form>
JavaScript
var expiryDate = document.getElementById("expiryDate").value;
if (!expiryDate.match(/^[0][1-9]|[1][0-2]-[0-9]{2}$/)){
errMsg = errMsg + "The expiry date needs to be mm-yy and consist of a valid date.\n";
result = false;
}
So if anyone has an idea of how to help me, I would appreciate it!
I'm always surprised at how programmers would rather spend their efforts building straight-jackets for users rather than writing user friendly code.
The month criteria seem to be incorrect, ">01 and <12" infers a value from 2 to 11 inclusive, I expect that ">=1 and <=12" was intended.
To do exactly what the assignment requires, you could do something like:
/* Check that the provided string is:
** - exactly 2-2 digits in the format mm-yy
** - mm is >= 01 and <= 12
** - expiry date is this month or later
*/
function validateExpiryDate(s) {
// Check 2-2 digits
if (!/\d\d-\d\d/.test(s)) {
return 'Expiry date format must be MM-YY: ' + s;
}
// Check month is 1 to 12 inclusive
var b = s.split('-');
if (b[0]<1 || b[0]>12) {
return 'Expiry month must be from 00 to 12: ' + b[0];
}
// Check is this month or later
var d = new Date()
var c = d.getFullYear()/100 | 0 + '';
if (new Date(c + b[1], b[0], 1) < d) {
return 'Expiry date must be this month or later: ' + s;
}
return true;
}
// Some tests
['01-17','12-17','foo','13-20','9-18'].forEach(function(s){
console.log(validateExpiryDate(s));
})
However, to be a little more user friendly, you can accept single digits and various separators quite easily. Also, you can just cut to the chase and test whether the value entered generates a suitable expiry date. You can also reformat the entered string into the required format, e.g.:
// Validate expiry date in m-yy format
// Separator can be any non-digit
function checkExpiryDate(s) {
var b = s.split(/\D/);
var d = new Date();
var century = d.getFullYear()/100 | 0;
// Generate date for first day of following month
var expires = new Date(century + b[1], b[0], 1);
return d < expires;
}
// Reformat date in m/yy format to mm-yy strict
function formatExpiry(s) {
var b = s.split(/\D/);
function z(n){return (n<10?'0':'') + +n}
return z(b[0]) + '-' + z(b[1]);
}
['1/1','4-17','03-17','3-18','06/19','3.19','foo'].forEach(function(s) {
console.log('String "' + s + '" converts to "' +
formatExpiry(s) + '" and is ' +
(checkExpiryDate(s)? '' : 'not ') + 'valid.');
});
So being user friendly is also less code to write. ;-)
Calculating the century is a bit of overkill, you could just use "20" and expect that your code will not be running in 2095 when expiry dates will start having centuries of "21".
Something like this should help
var today = new Date(); // gets the current date
var today_mm = today.getMonth() + 1; // extracts the month portion
var today_yy = today.getFullYear() % 100; // extracts the year portion and changes it from yyyy to yy format
if(today_mm < 10) { // if today's month is less than 10
today_mm = '0' + today_mm // prefix it with a '0' to make it 2 digits
}
var mm = expiryDate.substring(0, 2); // get the mm portion of the expiryDate (first two characters)
var yy = expiryDate.substring(3); // get the yy portion of the expiryDate (from index 3 to end)
if (yy > today_yy || (yy == today_yy && mm >= today_mm)) {
// all good because the yy from expiryDate is greater than the current yy
// or if the yy from expiryDate is the same as the current yy but the mm
// from expiryDate is greater than the current mm
}
else
{
errMsg = errMsg + "The expiry date needs to be greater than today.\n";
result = false;
}

Moment.js how to get week of month? (google calendar style)

I am using Moment.js and it is great. The problem I have now is that I can't figure out how to get the week of the month a certain date is. I can only find "week of year" in the Moment js docs. For example, if I choose today's date (2/12/2014), I would like to know that this date is in the second week of this month of february and consequently, it is the second wednesday of the month. Any ideas?
EDIT:
I guess some clarification is necessary. What I need most is the nth number of a certain day in a month. For example, (from the comments) Feb 1, 2014 would be the first Saturday of the month. Feb 3, 2014 would be the first Monday of the month even though it is "technically" the second week of the month. Basically, exactly how google calendar's repeat function classifies days.
It seems that moment.js does not have the method that implements the functionality that you are looking for.
However, you can find the nth number of a certain day of the week in a month is using the Math.ceil of the date / 7
For example:
var firstFeb2014 = moment("2014-02-01"); //saturday
var day = firstFeb2014.day(); //6 = saturday
var nthOfMoth = Math.ceil(firstFeb2014.date() / 7); //1
var eightFeb2014 = moment("2014-02-08"); //saturday, the next one
console.log( Math.ceil(eightFeb2014.date() / 7) ); //prints 2, as expected
It looks like this is the number you are looking for, as demonstrated by the following test
function test(mJsDate){
var str = mJsDate.toLocaleString().substring(0, 3) +
" number " + Math.ceil(mJsDate.date() / 7) +
" of the month";
return str;
}
for(var i = 1; i <= 31; i++) {
var dayStr = "2014-01-"+ i;
console.log(dayStr + " " + test(moment(dayStr)) );
}
//examples from the console:
//2014-01-8 Wed number 2 of the month
//2014-01-13 Mon number 2 of the month
//2014-01-20 Mon number 3 of the month
//2014-01-27 Mon number 4 of the month
//2014-01-29 Wed number 5 of the month
When calculating the week of the month based on a given date, you have to take the offset into account. Not all months start on the first day of the week.
If you want to take this offset into account, you can use something something like the following if you are using moment.
function weekOfMonth (input = moment()) {
const firstDayOfMonth = input.clone().startOf('month');
const firstDayOfWeek = firstDayOfMonth.clone().startOf('week');
const offset = firstDayOfMonth.diff(firstDayOfWeek, 'days');
return Math.ceil((input.date() + offset) / 7);
}
Simple using moment.js
function week_of_month(date) {
prefixes = [1,2,3,4,5];
return prefixes[0 | moment(date).date() / 7]
}
This library adds the function moment.weekMonth()
https://github.com/c-trimm/moment-recur
I made some modifications based on feedback.
let weeks = moment().weeks() - moment().startOf('month').weeks() + 1;
weeks = (weeks + 52) % 52;
On days passing through the next year, the week value will be negative so I had to add 52.
What about something like:
weekOfCurrentMonth = (moment().week() - (moment().month()*4));
This takes the current week of the year, and subtracts it by the 4 times the number of previous months. Which should give you the week of the current month
I think the answer to this question will be helpful, even though it doesn't use moment.js as requested:
Get week of the month
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
There is a problem with #Daniel Earwicker answer.
I was using his function in my application and the while loop was infinite because of the following situation:
I was trying to figure out which week of december (2016) was the day 31.
the first day of december was day 336 of the year. The last day of december was day 366 of the year.
Problem here: When it was day 366 (31 of december, last day of the year) the code added another day to this date. But with another day added it would be day 1 of january of 2017. Therefore the loop never ended.
while (m.dayOfYear() <= yearDay) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
I added the following lines to the code so the problem would be fixed:
function countWeekdayOccurrencesInMonth(date) {
var m = moment(date),
weekDay = m.day(),
yearDay = m.dayOfYear(),
year = m.year(),
count = 0;
m.startOf('month');
while (m.dayOfYear() <= yearDay && m.year() == year) {
if (m.day() == weekDay) {
count++;
}
m.add('days', 1);
}
return count;
}
It verifies if it is still in the same year of the date being veryfied
Here's Robin Malfait's solution implemented with the lightweight library date-fns
import {
differenceInDays,
startOfMonth,
startOfWeek,
getDate
} from 'date-fns'
const weekOfMonth = function (date) {
const firstDayOfMonth = startOfMonth(date)
const firstDayOfWeek = startOfWeek(firstDayOfMonth)
const offset = differenceInDays(firstDayOfMonth, firstDayOfWeek)
return Math.ceil((getDate(date) + offset) / 7)
}
export default weekOfMonth
I'd do the following:
let todaysDate = moment(moment.now());
let endOfLastMonth = moment(get(this, 'todaysDate')).startOf('month').subtract(1, 'week');
let weekOfMonth = todaysDate.diff(endOfLastMonth, 'weeks');
That gets todaysDate and the endOfLastMonth and then uses Moment's built-in diff() method to compute the current month's week number.
It's not built-in, but basically you can subtract the week number of the start of the month from the week number of the date in question.
function weekOfMonth(m) {
return m.week() - moment(m).startOf('month').week() + 1;
}
Credit goes to code by original author, give him a star if it helped you.
How about this?
const moment = require("moment");
// Generate Week Number of The Month From Moment Date
function getWeekOfMonth(input = moment()) {
let dayOfInput = input.clone().day(); // Saunday is 0 and Saturday is 6
let diffToNextWeek = 7 - dayOfInput;
let nextWeekStartDate = input.date() + diffToNextWeek;
return Math.ceil((nextWeekStartDate) / 7);
}
Simple code, but has been working for me.
const weekOfTheMonth = (myMomentDate) => {
const startDay = moment(myMomentDate).startOf('week');
const day = parseInt(startDay.format('DD'),10);
if(day > 28){
return 5;
}
if((day > 21) && (day <= 28) ){
return 4;
}
if((day > 14) && (day <= 21) ){
return 3;
}
if((day > 7) && (day <= 14) ){
return 2;
}
return 1;
}

To check if age is not less than 13 years in javascript

Can anyone please guide me through javascript function, which will fetch me year difference between current date and date entered by user
I have tried this, but it doesnot keep in count leap years
var yearOld=2000
var dateOld=11
var mnthOld=1;
var currendDate=new Date(); // 9 - jan - 2013
var oldDate=new Date(yearOld,mnthOld-1,dateOld);
var timeDiff =currendDate-oldDate ;
var diffDays = timeDiff / (1000 * 3600 * 24 * 365);
Result is coming 13.00789 something where it should come less than 13
Any help will be appreciated
function getAge(birthDateString) {
var today = new Date();
var birthDate = new Date(birthDateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
if(getAge("27/06/1989") >= 18) {
alert("You have 18 or more years old!");
}
If you have good amount of Date related operations, consider using MomentJS http://momentjs.com/ . Check the first two examples there and i guess they fit your question.
http://www.datejs.com/ is a useful library for all kinds of calculations with dates
Use
// millisecs * secs * mins * hrs * days (inclu. leap)
msecsInYear = 1000 * 60 * 60 * 24 * 365.25;
Note: Statically not correct, but is mathematically correct!
Will cover leap year cases.
// 1. Get current date
// 2. Add 13 to the year in DOB.
// 3. check if current year is less than dob-year. If not person is older than 13 years
// 4. And so on check for month and date
var date_of_birth = '2015-12-26' // example DOB
var is_13 = true; // flag for 13
dob = date_of_birth.trim(); // trim spaces form DOB
y = parseInt(dob.substr(0,4)); // fetch year using substr() from DOB
m = parseInt(dob.substr(5,2)); // fetch month using substr() from DOB
d = parseInt(dob.substr(8,2)); // fetch date using substr() from DOB
// the above logic can change depending on the format of the input DOB
var r = new Date(); // Gets current Date
if(r.getFullYear() <= (parseInt(y) + 13)){
if((r.getMonth()+1) <= m){
if(r.getDate() < d){
is_13 = false;
console.log('less than 13');
}}}

EOFY age based on date of birth

I'm trying to get an age based on the end of the financial year.
If my date of birth is the 16th Jan 1962 my current age is 50 (assuming today's date is the 16th Jan 2012). What javascript formula/function could I use to calculate the age at the end of the current financial year (ie. 30th June 2012)?
This is what I have to get the current age:
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
alert("current age "+age)
}
You would use the end of the current financial year as the "today" date, right? And then the end of the current financial year would either be hardcoded into the function, or figured out programmatically.
You simply need to calculate the difference between two dates:
function ageAtEOFY(birthDate) {
var eofy = new Date("2012-06-30");
var msDiff = eofy - new Date(birthDate);
return Math.floor(msDiff / 1000 / 60 / 60 / 24 / 365.25);
}
Used like this:
ageAtEOFY("1962-01-16"); // 50
ageAtEOFY("1984-11-14"); // 27
The way this works is that eofy - new Date(birthDate) gives you the difference between the two dates in milliseconds. The rest is just converting that value into years.
Note that there's a bit of a fudge here: leap years don't simply occur every four years.

Categories

Resources