I have inherited a form that has some existing JavaScript that creates a new date + 3 months from today's date.
var monthAway = new Date(new Date);
var day =monthAway.getDate();
var month =monthAway.getMonth() + 3;
var year =monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
Issue is that if today's date is in October, November or December new date month will be 13, 14 or 15 rather than updating the to 1, 2 or 3 and then updating the year, e.g. 5/11/2014 is 05/14/2014 rather than 05/02/2015.
Any ideas?
Try this:
var x = 3; //or whatever offset
var CurrentDate = new Date();
CurrentDate.setMonth(CurrentDate.getMonth() + x);
alert(CurrentDate);
Add 3 months to monthAway variable using setMonth method as below
monthAway.setMonth(monthAway.getMonth() + 3);
then simply use the modified monthAway to display the expiration date. Please note that getMonth() Method will return 0-11 where 0 is January, 1 is February, ... , 11 is December, so you need to do this to display the correct month
var month = monthAway.getMonth() + 1;
This is the complete modified code, the value of #Date_for_Second_Store_Access_to_Expire would be 5/2/2015 assuming the code is executed today (5/11/2014).
var monthAway = new Date(new Date);
monthAway.setMonth(monthAway.getMonth() + 3); // add 3 months to monthAway
var day = monthAway.getDate();
var month = monthAway.getMonth() + 1; // add 1 because .getMonth returns zero based month
var year = monthAway.getFullYear();
$('#Date_for_Second_Store_Access_to_Expire').val(day + "/" + month + "/" + year);
<p><input id="Date_for_Second_Store_Access_to_Expire" type="hidden" name="Date_for_Second_Store_Access_to_Expire" class="required" /></p>
This is the JSFiddle that shows the value of day + "/" + month + "/" + year from the above code: http://jsfiddle.net/jwa6o6r2/
Just do a simple check when increasing the month variable:
var month = monthAway.getMonth() + 3;
if(month > 12) //If it crosses 12, start from 1 again.
month -= 12;
Change
var month = monthAway.getMonth() + 3;
To
var month = ((monthAway.getMonth() + 3) % 12) + 1;
The ((monthAway.getMonth() + 3) % 12) will give you a number from 0 to 11. Since you want 1 - 12, that's where the + 1 comes in.
For the year issue, try the following
var year = (month <= 3 ? monthAway.getFullYear() + 1 : monthAway.getFullYear());
This will check if the month is less than or equal to 3, which would only be possible if you've wrapped around.
Related
I tried this javascript to display the day of the week from 3 days before the html page is accessed. It doesn't work when today is Sunday, Monday or Tuesday.
(I think the problem is that the days are numbered 0-6 with no consideration of negative numbers in the line var date)
var now = new Date();
var days = new Array(
'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
var months = new Array(
'January','February','March','April','May',
'June','July','August','September','October',
'November','December');
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
function fourdigits(number) {
return (number < 1000) ? number + 1900 : number;}
today = days[now.getDay() -3] + ", " +
months[now.getMonth()] + " " +
date + ", " +
(fourdigits(now.getYear()));
document.write(today);
There are a number of issues with your code.
<SCRIPT LANGUAGE="JavaScript">
The language attribute for script elements was deprecated in HTML 4 and removed in subsequent versions.
<!--
HTML comment delimiters are tolerated at the start and end of script elements but should not be used. They have been unnecessary for 20 years.
var date = ((now.getDate()<10) ? "0" : "")+ now.getDate()-3;
When the date is 1 to 3, the first part of the expression will return a string like "0" or "". The second part will return a number from -2 to 0, so the result will be "0-2" to "00".
You can do something like:
var date = now.getDate();
date = (date < 10? '0' : '') + date;
Then there is:
today = days[now.getDay() -3] + ", " +
getDay returns a number representing the day of the week, 0 for Sunday to 6 for Saturday, so from Sunday to Tuesday (day numbers 0–2) you'll be attempting to access a property of days that doesn't exist, which will return undefined.
(fourdigits(now.getYear()));
getYear always returns the year less 1900. Use getFullYear instead.
See Where can I find documentation on formatting a date in JavaScript? and Add +1 to current date.
You should start by subtracting 3 days from the date, then format the result for output:
var now = new Date();
now.setDate(now.getDate() - 3);
var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday', 'Friday','Saturday'];
var months = ['January','February','March','April','May','June','July',
'August','September','October','November','December'];
var date = now.getDate();
date = (date < 10? "0" : "") + date;
var today = days[now.getDay()] + ", " +
months[now.getMonth()] + " " +
date + ", " + now.getFullYear();
document.write(today);
I know there are a lot of threads about finding the date of a specific day of the week in javascript but the all give it in the format like so:
Sun Dec 22 2013 16:39:49 GMT-0500 (EST)
but I would like it in this format 12/22/2013 -- MM/dd/yyyy
Also I want the most recent Sunday and the code I have been using does not work all the time. I think during the start of a new month it screws up.
function getMonday(d) {
d = new Date(d);
var day = d.getDay(),
diff = d.getDate() - day + (day == 0 ? -6:0); // adjust when day is sunday
return new Date(d.setDate(diff));
}
I have code that gives me the correct format but that is of the current date:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
this prints:
>>> 12/23/2013
when I try to subtract numbers from the day it does not work, so I cannot get the dat of the most recent Sunday as MM/dd/yyyy
How do I get the date of the most recent sunday in MM/dd/yyyy to print, without using special libraries?
You can get the current weekday with .getDay, which returns a number between 0 (Sunday) and 6 (Saturday). So all you have to do is subtract that number from the date:
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
Complete example:
var currentTime = new Date()
currentTime.setDate(currentTime.getDate() - currentTime.getDay());
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
console.log(month + "/" + day + "/" + year)
// 12/22/2013
To set the date to any other previous weekday, you have to compute the number of days to subtract explicitly:
function setToPreviousWeekday(date, weekday) {
var current_weekday = date.getDay();
// >= always gives you the previous day of the week
// > gives you the previous day of the week unless the current is that day
if (current_weekday >= weekday) {
current_weekday += 6;
}
date.setDate(date.getDate() - (current_weekday - weekday));
}
To get the date of next Sunday you have to compute the number of days to the next Sunday, which is 7 - currentTime.getDay(). So the code becomes:
currentTime.setDate(currentTime.getDate() + (7 - currentTime.getDay()));
Subtract days like this
// calculate days to subtract as per your need
var dateOffset = (24*60*60*1000) * 5; //5 days
var date = new Date();
date.setTime(date.getTime() - dateOffset);
var day = date.getDate() // prints 19
var month = date.getMonth() + 1
var year = date.getFullYear()
document.write(month + '/' + day + '/' + year);
Here is my suggestion. Create a function like so... in order to format any date you send it.
function formatDate(myDate) {
var tmp = myDate;
var month = tmp.getMonth() + 1;
var day = tmp.getDate();
var year = tmp.getFullYear();
return (month + "/" + day + "/" + year);
}
Now, to print the current date, you can use this code here:
var today = new Date();
var todayFormatted = formatDate(today);
To get the previous Sunday, you can use a while loop to subtract a day until you hit a Sunday, like this...
var prevSunday = today;
while (prevSunday.getDay() !== 0) {
prevSunday.setDate(prevSunday.getDate()-1);
}
var sundayFormatted = formatDate(prevSunday);
To see the whole thing together, take a look at this DEMO I've created...
** Note: Make sure you turn on the Console tab when viewing the demo. This way you can see the output.
You can create prototype functions on Date to do what you want:
Date.prototype.addDays = function (days) {
var d = new Date(this.valueOf());
d.setDate(d.getDate() + days);
return d;
}
Date.prototype.getMostRecentPastSunday = function () {
var d = new Date(this.valueOf());
return d.addDays(-d.getDay()); //Sunday is zero
}
Date.prototype.formatDate = function () {
var d = new Date(this.valueOf());
//format as you see fit
//http://www.webdevelopersnotes.com/tips/html/10_ways_to_format_time_and_date_using_javascript.php3
//using your approach...
var month = d.getMonth() + 1
var day = d.getDate()
var year = d.getFullYear()
return month + "/" + day + "/" + year;
}
console.log((new Date()).getMostRecentPastSunday().formatDate());
console.log((new Date("1/3/2014")).getMostRecentPastSunday().formatDate());
//or...
var d = new Date(); //whatever date you want...
console.log(d.getMostRecentPastSunday().formatDate());
Something like this will work. This creates a reusable dateHelper object (you will presumably be adding date helper methods since you don't want to use a library off the shelf). Takes in a date, validates that it is a date object, then calculates the previous Sunday by subtracting the number of millis between now and the previous Sunday.
The logging at the bottom shows you how this works for 100 days into the future.
var dateHelper = {
getPreviousSunday: function (date) {
var millisInADay = 86400000;
if (!date.getDate()) {
console.log("not a date: " + date);
return null;
}
date.setMilliseconds(date.getMilliseconds() - date.getDay() * millisInADay);
return date.getMonth() + 1 + "/" + date.getDate() + "/" + date.getFullYear();
}
}
var newDate = new Date();
console.log(dateHelper.getPreviousSunday(newDate));
var now = newDate.getTime();
for (var i=1; i<100; i++) {
var nextDate = new Date(now + i * 86400000);
console.log("Date: + " nextDate + " - previous sunday: " + dateHelper.getPreviousSunday(nextDate));
}
var now = new Date();
var dateString = now.getMonth() + "-" + now.getDate() + "-" + now.getFullYear() + " "
+ now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
here month is not displayed correctly.
Example if output is december it prints november
now.getMonth() +1 would display the correct month.
I am looking for a more better approach.
My application has to choose between two radiobuttons.the first option should return the current system date and time and other returns date and time selected from jsp.
On selecting either of the two options,it should return a date in a specific format to the controller.
getMonth() by definition returns month from 0 to 11.
If you are not used to this, you can change the prototype of a Date object:
Date.prototype.getFixedMonth = function(){
return this.getMonth() + 1;
}
new Date().getFixedMonth(); //returns 12 (December)
new Date("January 1 2012").getFixedMonth //returns 1 (January)
But this is not recommended at all.
Another approach
You can do this too if you want:
Date.prototype._getMonth = Date.prototype.getMonth;
Date.prototype.getMonth = function(){ //override the original function
return this._getMonth() + 1;
}
new Date().getMonth(); //returns 12 (December)
new Date("January 1 2012").getMonth //returns 1 (January)
getMonth() is supposed to return the Month as index from 0 to 11 (0 is January and 11 is December). So, what you're getting is the expected return value.
Here is the Function
function GetTime_RightNow() {
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
alert(month + "/" + day + "/" + year)
}
In my form I have a datafield where I select the day of the week!
For example if I select today 23-03-2012 Friday, I need to get an array of days from previous Monday to this next Saturday.
array:
[0],[19-03-2012],[Monday]
[1],[20-03-2012],[Monday]
[2],[21-03-2012],[Wednesday]
[3],[22-03-2012],[Monday]
[4],[23-03-2012],[Friday]
[5],[24-03-2012],[Saturday]
How can i do it for any selected day of the week obviously paying attention to changes?
Thanks
This function will return an array of all the dates in the week of date, Monday to Saturday.
function GetDaysOfWeek(date)
{
var days = new Array();
for (var i = 0; i < 6; i++)
{
days[i] = new Date(date.getYear(),
date.getMonth(),
date.getDate() - date.getDay() + 1 + i);
}
return days;
}
mayby try out MomentJs: http://momentjs.com/docs/
some examples:
moment().day(-7); // set to last Sunday (0 - 7)
moment().day(7); // set to next Sunday (0 + 7)
moment().day(10); // set to next Wednesday (3 + 7)
moment().day(24); // set to 3 Wednesdays from now (3 + 7 + 7 + 7)
For display the current day of the week:
var now = new Date();
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.write("Today is " + dayNames[now.getDay()] + ".");
First find todays date
Find the last monday (including today)
Show that date, and the next 5 days after it (Tuesday-Saturday)
var d = new Date();
if (d.getDay()==0){
d.setDate(d.getDate() + 1);
}
while (d.getDay() != 1){
d.setDate(d.getDate() - 1);
}
var days = new Array();
for (var i = 0; i < 6; i++){
days[i] = d.getDate() + i;
}
return days;
try this :
var dayString = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var now = new Date();
var currentDay = now.getDay(); // return 0 for Sunday, 6 for Saturday
var result = [];
var tempDate = new Date(now.getTime());
tempDate.setDate(now.getDate()-(currentDay+6)%7); // now tempDate is previous Monday
while(tempDate.getDay()!=0) {
var currentMonth = tempDate.getMonth()+1;
if(currentMonth<10) currentMonth = "0"+currentMonth;
result.push([tempDate.getDay()-1,tempDate.getDate()+"-"+currentMonth+"-"+tempDate.getFullYear(),dayString[tempDate.getDay()]]);
tempDate.setDate(tempDate.getDate()+1);
}
console.log(result);
Something like the following will do the trick, I"m sure you can get the formatting to where you want it.
// Assuming d is a date object
function getDateArray(din) {
// Add leading zero to one digit numbers
function aZ(n){return (n<10? '0':'') + n;}
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var d = new Date(din); // Don't wreck input date
var dn = d.getDay();
var a = [];
var i = 6; // length of day array
if (!dn) {
// It's Sunday, what now?
return ['Sunday!'];
}
d.setDate(d.getDate() + 6 - dn); // Next Saturday
do {
a[i--] = i + ' ' + aZ(d.getDate()) +
'-' + aZ(d.getMonth() + 1) +
'-' + d.getFullYear() +
' ' + days[d.getDay()];
d.setDate(d.getDate() - 1);
} while (i);
return a;
}
// Test it
var date = new Date(2012,2,2)
alert( date + '\n\n' + getDateArray(date).join('\n'));
/*
Fri Mar 02 2012 00:00:00
0 27-02-2012 Monday
1 28-02-2012 Tuesday
2 29-02-2012 Wednesday
3 01-03-2012 Thursday
4 02-03-2012 Friday
5 03-03-2012 Saturday
*/
I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)