getDay () unexpected output on the last day of the month - javascript

I have a script that gives me the days of the week, when I enter the day from 1 to 30 there are no problems, but when I enter the 31st, the script returns the first day of the same month.
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
let initialDate = new Date();
initialDate.setDate(numDayOfMonth);
initialDate.setMonth(4);
const numDayOfWeek = initialDate.getDay();
console.log(initialDate);
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}
Current output
Sat May 01 2021 20:40:48 GMT-0500 (Colombia Standard Time)
Expected output
Mo May 31 2021 20:40:48 GMT-0500 (Colombia Standard Time)

new Date() would use today's date initially, so that would be 15th June 2021. When you then try to set the Day to the 31st it wraps back to 01 because June only has 30 days.
To get your expected output you should set the Month first.

Your code is working as expected. I will explain.
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
let initialDate = new Date(); // initialDate will be 15/06/2021
initialDate.setDate(numDayOfMonth); // initialDate will be 01/07/2021, because 31/06/2021 doesn't exist
initialDate.setMonth(4); // initialDate will be 01/05/2021
const numDayOfWeek = initialDate.getDay();
console.log(initialDate);
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}

This is happening because you are setting the day first, then the month, which means you are setting it to the 31st day of the current month. If the current month has 30 days, it will roll over to 1.
Instead, use the constructor to specify the values:
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
const today = new Date();
const initialDate = new Date(today.getFullYear(), 4, numDayOfMonth);
const numDayOfWeek = initialDate.getDay();
console.log(initialDate.toLocaleString());
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}
myFunction();

Related

How to convert "dd/mm/yyyy" to ISO string in JavaScript

How can I convert this date: 29/12/2022 where:
29 is day,
12 is month,
2022 is year,
to ISO string.
I tried this:
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
console.log(myDate.toISOString());
// 2024-05-11T22:00:00.000Z this is wrong
I was expecting different result.
There is no need to parseInt and to remove 1 to the month.
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(`${parts[2]}-${parts[1]}-${parts[0]}`);
console.log(myDate.toISOString());
In my code usually I do something like this:
const dateStr = "29/12/2022";
const parts = dateStr.split("/");
const date = new Date(0); // It will set hours, minutes, and seconds to 0
date.setDate(parts[0]);
date.setMonth(parts[1]-1);
date.setFullYear(parts[2]);
console.log(date.toISOString());
It may not be the most optimal way but you could do it this way as long as the month when it is a single digit is sent with zero at the beginning type: 01 -> January
let date = '29/12/2022';
let dateFormat = date[3]+date[4]+"-"+date[0]+date[1]+"-
"+date[6]+date[7]+date[8]+date[9]
// 12-29-2022
let mydate = new Date(dateFormat)
// Thu Dec 29 2022 00:00:00 GMT-0500

startOfMonth returns last day of month before

So it's pretty straight forwards:
import startOfMonth from 'date-fns/start_of_month';
export const getFirstDayThisMonth = date => {
const firstDay = startOfMonth(date);
return firstDay;
};
given input (for example):
1987-02-02T00:00:00.000Z
it returns:
1987-01-31T23:00:00.000Z
The error is reproduced exactly when trying to produce the first date according to the method mentioned in this answer:
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
The error comes when running jest-tests and can't be reproduced in the console where it works as expected:
const day1 = new Date('1987-02-02');
undefined
const day2 = new Date(day1.getFullYear(),day1.getMonth(),1)
undefined
day2
Sun Feb 01 1987 00:00:00 GMT+0100 (Central European Standard Time)
If in the second solution I also set the fourth argument (hour) to 1, it correctly handles:
1987-02-02T00:00:00.000Z
returning 1987-02-01T00:00:00.000Z
and
2001-03-03T00:00:00.000Z
returning 2001-03-01T00:00:00.000Z
but
2002-04-04T00:00:00.000Z
returns 2002-03-31T23:00:00.000Z
I'm really at loss as to what could be causing this issue, it feels like there's some rollover to the previous date when the time is set to 00:00:00?
Per request, here's the date-fns-code for startOfMonth:
function startOfMonth (dirtyDate) {
var date = parse(dirtyDate)
date.setDate(1)
date.setHours(0, 0, 0, 0)
return date
}
I really don't get why
var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1, 1);
seem to work on feb-march but not on april?

Add A Year To Today's Date

I am trying to add a year to todays date. I am working in a system that does not allow you to use standard JavaScript.
For instance, to get todays date I have to use:
javascript:now();
I have tried:
javascript:now(+1);
I have never seen this before, but am in need of adding one year to todays date...
Has anyone seen getting current date this way before? And if so, how could I add a year?
Use the Date.prototype.setFullYear method to set the year to what you want it to be.
For example:
const aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
console.log(aYearFromNow);
There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.
You can create a new date object with todays date using the following code:
var d = new Date();
console.log(d);
// => Sun Oct 11 2015 14:46:51 GMT-0700 (PDT)
If you want to create a date a specific time, you can pass the new Date constructor arguments
var d = new Date(2014);
console.log(d)
// => Wed Dec 31 1969 16:00:02 GMT-0800 (PST)
If you want to take todays date and add a year, you can first create a date object, access the relevant properties, and then use them to create a new date object
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var c = new Date(year + 1, month, day);
console.log(c);
// => Tue Oct 11 2016 00:00:00 GMT-0700 (PDT)
You can read more about the methods on the date object on MDN
Date Object
One liner as suggested here
How to determine one year from now in Javascript
by JP DeVries
new Date(new Date().setFullYear(new Date().getFullYear() + 1))
Or you can get the number of years from somewhere in a variable:
const nr_years = 3;
new Date(new Date().setFullYear(new Date().getFullYear() + nr_years))
This code adds the amount of years required for a date.
var d = new Date();
// => Tue Oct 01 2017 00:00:00 GMT-0700 (PDT)
var amountOfYearsRequired = 2;
d.setFullYear(d.getFullYear() + amountOfYearsRequired);
// => Tue Oct 01 2019 00:00:00 GMT-0700 (PDT)
I like to keep it in a single line, you can use a self calling function for this eg:
If you want to get the timestamp of +1 year in a single line
console.log(
(d => d.setFullYear(d.getFullYear() + 1))(new Date)
)
If you want to get Date object with single line
console.log(
(d => new Date(d.getFullYear() + 1, d.getMonth(), d.getDate()))(new Date)
)
In Angular, This is how you Calculate Date
today = new Date();
year = this.today.getFullYear();
month = this.today.getMonth();
day = this.today.getDate();
//To go 18 years back
yearsBack18= new Date(this.year - 18, this.month, this.day);
//To go to same day next year
nextYear= new Date(this.year + 1, this.month, this.day);
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var fulldate = new Date(year + 1, month, day);
var toDate = fulldate.toISOString().slice(0, 10);
$("#txtToDate").val(toDate);
output : 2020-01-02
//This piece of code will handle the leap year addition as well.
function updateExpiryDate(controlID, value) {
if ( $("#ICMEffectiveDate").val() != '' &&
$("#ICMTermYears").val() != '') {
var effectiveDate = $("#ICMEffectiveDate").val();
var date = new Date(effectiveDate);
var termYears = $("#ICMTermYears").val();
date = new Date(date.setYear(date.getFullYear() + parseInt(termYears)));
var expiryDate = (date.getMonth() + 1) + '/' + date.getDate() + '/' + date.getFullYear();
$('#ICMExpiryDate').val(expiryDate);
}
}
var yearsToAdd = 5;
var current = new Date().toISOString().split('T')[0];
var addedYears = Number(this.minDate.split('-')[0]) + yearsToAdd + '-12-31';

How To add number of month into the given date in javascript?

I want to add month into the select date by the user.
startdate=document.getElementById("jscal_field_coverstartdate").value;
now I want to add 11 month from the above startdate. How to do that.
date format = 2013-12-01
Without the date format it is difficult to tell, however you can try like this
add11Months = function (date) {
var splitDate = date.split("-");
var newDate = new Date(splitDate[0], splitDate[1] - 1, splitDate[2]);
newDate.setMonth(newDate.getMonth() + 11);
splitDate[2] = newDate.getDate();
splitDate[1] = newDate.getMonth() + 1;
splitDate[0] = newDate.getFullYear();
return startdate = splitDate.join("-");
}
var startdate = add11Months("2013-12-01");
alert(startdate)
JSFiddle
If your startdate is in correct date format you can try using moment.js or Date object in javascript.
In Javascript, it can be achieved as follow:
var date = new Date("2013-12-01");
console.log(date);
//output: Sun Dec 01 2013 05:30:00 GMT+0530 (India Standard Time)
var newdate = date.setDate(date.getDate()+(11*30));
console.log(new Date(newdate));
// output: Mon Oct 27 2014 05:30:00 GMT+0530 (India Standard Time)
In above lines, I have used 30 days per month as default. So you will get exact 11 month but little deviation in date. Is this what you want ? You can play around this likewise. I hope it help :)
For more about Date you can visit to MDN.
You can do it like this:
var noOfMonths = 11
var startdate = document.getElementById("jscal_field_coverstartdate").value;
startdate.setMonth(startdate.getMonth() + noOfMonths)
Try this:
baseDate.setMonth(2);
baseDate.setDate(30);
noMonths = 11;
var sum = new Date(new Date(baseDate.getTime()).setMonth(baseDate.getMonth() + noMonths);
if (sum.getDate() < baseDate.getDate()) { sum.setDate(0); }
var m = newDate.getDate();
var d = newDate.getMonth() + 1;
var yyyy = newDate.getFullYear();
return (yyyy+"-"+m+"-"+d);
Notes:
Adding months (like adding one month to January 31st) can overflow the days field and cause the month to increment (in this case you get a date in March). If you want to add months and then overflow the date then .setMonth(base_date.getMonth()+noMonths) works but that's rarely what people think of when they talk about incrementing months.
It handles cases where 29, 30 or 31 turned into 1, 2, or 3 by eliminating the overflow
Day of Month is NOT zero-indexed so .setDate(0) is last day of prior month.

javascript: get month/year/day from unix timestamp

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}
var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).
Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.

Categories

Resources