How to get day of month from Date() [duplicate] - javascript

This question already has answers here:
How do I get the day of the month in javascript?
(4 answers)
Closed 2 years ago.
How to get day(number) of month from Date() in javascript?
i try this:
const date = new Date(`2020-07-21T08:08:20.794Z`);
const dayNumber = date.getDay(); //return me 2(day in week)
but it return me 2 instead of 21 :/
can someone help me?

I believe you want date.getDate() (I know the name is a bit confusing). Here's what I get:
asyncify:~ js$ node
Welcome to Node.js v12.10.0.
Type ".help" for more information.
> const date = new Date(`2020-07-21T08:08:20.794Z`);
undefined
> date.getDate()
21

date has a getDate method which is different from getDay method.
getDate returns day of the month.
getDay returns which day of the week.
const date = new Date(`2020-07-21T08:08:20.794Z`);
const dayNumber = date.getDate(); //return me 2(day in week)

Related

getMonth() in Javascript from format dd/mm/yyyy [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 3 years ago.
I have a date in format dd/mm/yyyy and when I try to use getMonth() I get the dd field.
For example if I have "01/12/2019" it will take 01 as month instead of 12. Is there a way to get the month from this format?
This is my code:
var beginDate = document.getElementById("beginDate").value;
var month = new Date(beginDate).getMonth();
inside beginDate there's "01/10/2019" (October 1st 2019)
It's better to use any external libraries like momentjs or datejs. Try this it may solve your problem now.
const date = "01/12/2019";
const split = date.split('/');
console.log('day', split[0])
console.log('month', split[1])
console.log('year', split[2])
var date = moment('01/12/2019', 'DD/MM/YYYY');
console.log(date.month()+1);
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
You can use something like Moment.js
const beginDate = "22/05/2019"
const date = moment(beginDate, 'DD/MM/YYYY');
const month = date.format('M');
console.log(month)
//05
Make it easy.
You don't need external libraries:
var beginDate = "01/10/2019";
var timeZone = 'your time zone'; //en-GB etc...
var month = new Date(beginDate).toLocaleString(timeZone , {month: "2-digit"}); //month = 10
I don't think that you need some external library to do this task. You should use javascript date object to get it done easily, getMonth() returns month indexed from 0 to 11. Prefer javascript always instead of unnecessarily importing external js files for libraries
var beginDate = document.getElementById("beginDate").value;
let reg = /(\d\d)\/(\d\d)\/(\d+)/gi;
const[date,mon,year] = reg.exec(beginDate).splice(1);
month = new Date(year,mon-1,date).getMonth(); // months are indexed from 0 to 11 for jan to dec
console.log(month); // 0 for jan and 11 for dec
Month in javascript is 0 indexed that mean 0 represent January, So you need to add 1 to get the month correctly
function getMonth(dt) {
let splitDt = dt.split('/');
return new Date(`${splitDt[2]}-${splitDt[1]}-${splitDt[0]}`).getMonth() + 1;
}
console.log(getMonth("01/10/2019"))
1st oct
You can get months using getMonth() as shown below, But here 0=January, 1=February etc.
var date = "05/12/2019"
var d = new Date(date);
var n = d.getMonth();
console.log(n)

Increment Month in JavaScript removes the DATE format using setMonth() [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
Below is my JavaScript Code to try and create a Maximum date where the user can't book past so many months into the future:
var x= 12;
var arriveDate = "28/11/2018"
var currentDate = new Date();
var a_date = new Date(arriveDate);
var max_month = currentDate.setMonth(currentDate.getMonth()+ x);
if (arriveDate === ""){
$("#arrive_date_error").html("Please don't leave this field blank");
}
else if (a_date < currentDate){
console.log("Please don't select a date in the past")
}
else if (a_date > max_month){
console.log("date in future")
}
The last else if never seems to work no matter what month/day/year I try. I decided to use console.log(max_month) to see what month it was creating and it returned:
1574953488195
Rather than the correct format:
Thu Nov 28 2019 15:04:48 GMT+0000
What am I doing wrong and why is it changing the format when I try to change the month of the date object?
setMonth mutates the currentDate, it does not return a new date. You probably want to clone the date and set the months of that cloned one:
var max_month = new Date(+currentDate);
max_month.setMonth(max_month.getMonth() + x);

javascript minus one month return first day of current month when month day is 31 [duplicate]

This question already has answers here:
Subtracting 1 month to 2015-12-31 gives 2015-12-01
(4 answers)
Closed 4 years ago.
Usually I minus one month from current date like below:
//assuming today is 2018-05-30T09:50:05.345Z
var d = new Date;
console.log(d);
// return : 2018-05-30T09:50:05.345Z
d.setUTCMonth( d.getUTCMonth() -1 );
console.log(d);
//return : 2018-04-30T09:50:05.345Z
but suppose, today is the 31 of the month and this doesn't work anymore... ex:
//assuming today is 2018-05-31T09:54:23.850Z
var d = new Date;
console.log(d);
// return : 2018-05-31T09:54:23.850Z
d.setUTCMonth( d.getUTCMonth() -1 );
console.log(d);
//return : 2018-05-01TT09:54:23.850Z
instead of setting date to previous month, date is set to first day of month (same append with d.setMonth(d.getMonth - 1)
what am I missing?
When you put static value like dateObj.setUTCMonth(4); it is showing the same i.e. 2018-05-01 but if we put var dateObj = new Date(); dateObj.setUTCMonth(dateObj.getUTCMonth()-1,30); console.log(dateObj); it works.This is JS issue. If you want to use the same code, you need to check the number of day in month & then execute the condition basis code.

Date comparison in javascript? [duplicate]

This question already has answers here:
What is the best way to determine if a date is today in JavaScript?
(5 answers)
Closed 7 years ago.
I have some date in milliseconds as 1425133515000 . Now in javascript I need to verify whether 1425133515000 is today or not. Is it possible?
I need one method which takes date in milli seconds and return true if date in milliseconds is today.
New date object from miliseconds:
var dateFromMs = new Date(1425133515000);
And comparsion based on How to know date is today?:
var today = new Date();
if (today.toDateString() === dateFromMs.toDateString()) {
alert('today');
}
You could use the Date constructor taking an Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC (Unix Epoch) - which is what your integer value represents:
vat date = new Date(1425133515000);
var now = new Date();
Now all that's left is compare is whether the 2 dates represent the same calendar day:
var isSameDay =
date.getDate() === now.getDate() &&
date.getMonth() === now.getMonth() &&
date.getFullYear() === now.getFullYear();

Get day from Date in JavaScript [duplicate]

This question already has answers here:
Convert dd-mm-yyyy string to date
(15 answers)
Closed 9 years ago.
I want to get day from date. Suppose my date is 03-08-2013 it is in d-mm-yyyy format so I just want to get dand that is 03 from above date so I try this code but it does not work
Note
I want to do it without including any js
var date = '08-03-2013';
var d = new Date(date);
alert(d.getDate());
// 2nd way
alert(date.getDate());
it alert NaN. What is missing in this code?
here is jsfiddel Link Jsfiddle Link
UPDATE
Date parsing in JS (and many languages, for that matter) is problematic because when the input is a date string, it's fairly ambiguous what piece of data is what. For example, using your date (August 3, 2013) it could be represented as
03-08-2013 (dd-mm-yyyy)
08-03-2013 (mm-dd-yyyy)
However, given just the date string, there's no way to tell if the date is actually August 3, 2013 or March 8, 2013.
You should pass your date values independently to guarantee the date is correctly parsed:
var
str = '08-03-2013',
parts = str.split('-'),
year = parseInt(parts[2], 10),
month = parseInt(parts[1], 10) - 1, // NB: month is zero-based!
day = parseInt(parts[0], 10),
date = new Date(year, month, day);
alert(date.getDate()); // yields 3
MDN documentation for Date
You can't know the regional settings of your visitors.
If you know the format of the string is always d-mm-yyyy then just parse the value yourself:
function GetDay(rawValue) {
var parts = rawValue.split("-");
if (parts.length === 3) {
var day = parseInt(parts[0], 10);
if (!isNaN(day))
return day;
}
alert("invalid date format");
return null;
}
Live test case.
Use moment.js. It's parsing ability is much more flexible than the Date class.
var m = moment('03-08-2013','DD-MM-YYYY');
var dayOfMonth = m.date();
Use this it that which you want..
var date = '08-03-2013';
date=date.replace(/([0-9]{2})\-([0-9]{2})\-([0-9]{4})/g, '$3-$2-$1');
var d = new Date(date);
alert(d.getDate());
Thanks

Categories