Hi I\'m new in javascript I have such javascript code
alert(DATE.value);
var d = new Date(DATE.value);
var year = d.getFullYear();
var month = d.getMonth();
I had a similar problem. date.getMonth()
returns an index ranging from 0 to 11
. January is 0
. If you create a new date()
-object and you want to get information about a costum date not the current one you have to decrease only the month by 1
.
Like this:
function getDayName () {
var year = 2016;
var month = 4;
var day = 11;
var date = new Date(year, month-1, day);
var weekday = new Array("sunday", "monday", "tuesday", "wednesday",
"thursday", "friday", "saturday");
return weekday[date.getDay()];
}
use .getDate
instead of .getDay
.
The value returned by getDay is an integer corresponding to the day of the week: 0 for Sunday, 1 for Monday, 2 for Tuesday, and so on.
getDay()
will give you the day of the week. You are looking for getDate()
.
function formatDate(date, callback)
{
var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
var day = weekday[date.getDay()];
console.log('day',day);
var d = date.getDate();
var hours = date.getHours();
ampmSwitch = (hours > 12) ? "PM" : "AM";
if (hours > 12) {
hours -= 12;
}
else if (hours === 0) {
hours = 12;
}
var m = date.getMinutes();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var month = months[date.getMonth()];
var year = date.getFullYear();
newdate = day + ', ' + month + ' ' + d + ',' + year + ' at ' + hours + ":" + m + " " + ampmSwitch
callback(newdate)
}
and call with this code
date="Fri Aug 26 2016 18:06:01 GMT+0530 (India Standard Time)"
formatDate(date,function(result){
console.log('Date=',result);
});
From now on you probably want to use the following below functions for Date objects:
function dayOf(date)
{
return date.getDate();
}
function monthOf(date)
{
return date.getMonth() + 1;
}
function yearOf(date)
{
return date.getYear() + 1900;
}
function weekDayOf(date)
{
return date.getDay() + 1;
}
var date = new Date("5/15/2020");
console.log("Day: " + dayOf(date));
console.log("Month: " + monthOf(date));
console.log("Year: " + yearOf(date));
getDay()
returns the day of the week. You can however use the getDate()
method.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getDay