show DD.MM.YYYY date + X days - javascript

Hi I have a code that shows date + 5 days in DD.MM format
Please help me to add current year to this code. DD.MM.YYYY
Year also should be like day and month and not this way + "2017"
<script>
function get(dday) {
var newdate = new Date();
newdate.setDate(newdate.getDate()+dday);
return newdate.getDate() + "." + ''+['01','02','03','04','05','06','07','08','09','10','11','12'][newdate.getMonth()];
}
</script>
<span><script type="text/javascript">document.write(get(5));</script></span>

Date.getFullYear returns the full year.
<script>
function get(dday) {
var newdate = new Date();
newdate.setDate(newdate.getDate()+dday);
function pad(value){
return ("0"+value).substring(value<10?0:1);
}
return [pad(newdate.getDate()),pad(newdate.getMonth()+1),newdate.getFullYear()].join(".");
}
</script>
<span><script type="text/javascript">document.write(get(5));</script></span>

Try this -
<script>
function get(dday) {
var newdate = new Date();
newdate.setDate(newdate.getDate()+dday);
return newdate.getDate() + "." + ''+['01','02','03','04','05','06','07','08','09','10','11','12'][newdate.getMonth()]+"."+newdate.getFullYear();
}
</script>
<span><script type="text/javascript">document.write(get(5));</script></span>
This outputs : 24.03.2017

Related

How to convert a date formatted (YYMMDD) as string but with 00 days?

I have a date formatted as string, eg: 240800. The date format for that string is YYMMDD. With the below code, I can convert the string to date but it doesn't always work in deducting 1 day. I need my output to be a valid date, not with 00 day. So with the date above, it should be converted and formatted to 07/31/2024.
Here's what I got so far.
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
var formattedDate = date.getMonth() + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
Working:
"240800" = 7/31/2024
All months from 4 to 12
Not Working:
"240100" = 0/31/2024 x
"240200" = 1/29/2024 x
"240300" = 2/31/2024 x
The reason is the date variable parameter in new Date() is counted as 0~11, not the general range,1~12.
So the working answer actually is wrong. It seems like being right just for July and August have 31 days.
The correct way is to firstly deduct 1 month and then calculate it. After all of the process is done, you can add 1 month in the end.
The below is working codes:
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
//deduct 1 month firstly
var month = Number(stringDate.substring(2,4))-1;
var day = stringDate.substring(4,6);
var date = new Date('20' + year, month, day);
//add 1 month finally
var formattedDate = date.getMonth()+1 + '/' + date.getDate() + '/' + date.getFullYear();
console.log(formattedDate);
}
formatDate('240100');
In python Assuming your string is yymmdd below function should do what you want. I am sure javascript has some module for date handling.
from datetime import datetime, timedelta
def fd(s):
d=datetime.strptime(s[:-2],'%y%m')+timedelta(days=int(s[-2:])-1)
return d.strftime('%m/%d/%Y')
Try this ..
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var d1;
if (day==="00")
{
d1 = new Date(month + '/01/20' + year);
d1.setDate(d1.getDate() -1);
//console.log("day1" + d1);
}
else
{
d1 = new Date('20' + year, month, day);
}
var formattedDate = d1.getMonth() + '/' + d1.getDate() + '/' + d1.getFullYear();
console.log(formattedDate);
}

How to get nth Weekday of Current date in javascript

I need to retrieve nth weekday of the current date in js. like 1st Sunday, 2nd Sunday
var d=new Date();
var weekDay=d.getDay();
here weekDay gives me 4 that means its Wednesday(3rd Wednesday). So far its good.
from weekDay i can say that its wednesday.
how to calcuate the "3rd" index of this wednesday?
Thank you
What du you actually mean? To get the dates you could use Date(). Like for instance creating a variable "today" and setting it to be todays date.
var today = new Date();
In a greater context you could go as far as showing everything from weekdays, date, year etc etc! I'll provide a code bit below. The code shows a dynamic clock/date in HTML.
You can format this the way you want, and choose which variables to show! This is btw the same code as found here: Other thread/question
<!DOCTYPE html>
<html>
<head>
<script>
function startTime() {
var today=new Date();
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = "Date: " + day + "/" + month + "/" + year + " " + "Clock: " + h+":"+m+":"+s;
var t = setTimeout(function(){startTime()},500);
}
function checkTime(i) {
if (i<10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
Is this what you mean?
Something like this
function getNth(dat) {
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday','saturday'],
nth = ['st', 'nd', 'rd', 'th', 'th'],
d = dat ? dat instanceof Date ? dat : new Date(dat) : new Date(),
date = d.getDate(),
day = d.getDay(),
n = Math.ceil(date / 7);
return n + nth[n-1] + ' ' + days[day];
}
document.body.innerHTML = '' +
'today ....: ' + getNth() + '<br>' +
'1/31/2015 : ' + getNth('1/31/2015') + '<br>' +
'1/16/2015 : ' + getNth('1/16/2015');
body {font-family: monospace}
As per my understanding you want what date will be 1st, 2nd sunday/Monday from today. If it is that then you can use this
//consider sun=o,mon=1,....,sat:6
function getWeekday(n,day)
{
var today = new Date();
var presentDay = today.getDay();
var presentTime = today.getTime();
if(day < presentDay)
{
day = day +6;
}
var diff = day - present day;
var daysAfter = (n-1)*7 + diff;
var timeAfter = presentTime+daysAfter*86400000;
var next date = new Date(timeAfter);
}
// if you want to get 1st sunday from today just call this
var sunday1 = getWeekday(1,0)
// to get second monday from today
var monday2 = getWeekday(2,1)

Get current date in DD-Mon-YYY format in Jquery [duplicate]

How can I format the date using jQuery. I am using below code but getting error:
$("#txtDate").val($.format.date(new Date(), 'dd M yy'));
Please suggest a solution.
add jquery ui plugin in your page.
$("#txtDate").val($.datepicker.formatDate('dd M yy', new Date()));
jQuery dateFormat is a separate plugin. You need to load that explicitly using a <script> tag.
An alternative would be simple js date() function, if you don't want to use jQuery/jQuery plugin:
e.g.:
var formattedDate = new Date("yourUnformattedOriginalDate");
var d = formattedDate.getDate();
var m = formattedDate.getMonth();
m += 1; // JavaScript months are 0-11
var y = formattedDate.getFullYear();
$("#txtDate").val(d + "." + m + "." + y);
see: 10 ways to format time and date using JavaScript
If you want to add leading zeros to day/month, this is a perfect example:
Javascript add leading zeroes to date
and if you want to add time with leading zeros try this:
getMinutes() 0-9 - how to with two numbers?
Here's a really basic function I just made that doesn't require any external plugins:
$.date = function(dateObject) {
var d = new Date(dateObject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "/" + month + "/" + year;
return date;
};
Use:
$.date(yourDateObject);
Result:
dd/mm/yyyy
I'm using Moment JS. Is very helpful and easy to use.
var date = moment(); //Get the current date
date.format("YYYY-MM-DD"); //2014-07-10
ThulasiRam, I prefer your suggestion. It works well for me in a slightly different syntax/context:
var dt_to = $.datepicker.formatDate('yy-mm-dd', new Date());
If you decide to utilize datepicker from JQuery UI, make sure you use proper references in your document's < head > section:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
I hope this code will fix your problem.
var d = new Date();
var curr_day = d.getDate();
var curr_month = d.getMonth();
var curr_year = d.getFullYear();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
var curr_sec = d.getSeconds();
curr_month++ ; // In js, first month is 0, not 1
year_2d = curr_year.toString().substring(2, 4)
$("#txtDate").val(curr_day + " " + curr_month + " " + year_2d)
Add this function to your <script></script> and call from where ever you want in that <script></script>
<script>
function GetNow(){
var currentdate = new Date();
var datetime = currentdate.getDate() + "-"
+ (currentdate.getMonth()+1) + "-"
+ currentdate.getFullYear() + " "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
return datetime;
}
window.alert(GetNow());
</script>
or you may simply use the Jquery which provides formatting facilities also:-
window.alert(Date.parse(new Date()).toString('yyyy-MM-dd H:i:s'));
I love the second option. It resolves all issues in one go.
If you are using jquery ui then you may use it like below, you can specify your own date format
$.datepicker.formatDate( "D dd-M-yy", new Date()) // Output "Fri 08-Sep-2017"
Just use this:
var date_str=('0'+date.getDate()).substr(-2,2)+' '+('0'+date.getMonth()).substr(-2,2)+' '+('0'+date.getFullYear()).substr(-2,2);
Though this question was asked a few years ago, a jQuery plugin isn't required anymore provided the date value in question is a string with format mm/dd/yyyy (like when using a date-picker);
var birthdateVal = $('#birthdate').val();
//birthdateVal: 11/8/2014
var birthdate = new Date(birthdateVal);
//birthdate: Sat Nov 08 2014 00:00:00 GMT-0500 (Eastern Standard Time)
You can add new user jQuery function 'getDate'
JSFiddle: getDate jQuery
Or you can run code snippet. Just press "Run code snippet" button below this post.
// Create user jQuery function 'getDate'
(function( $ ){
$.fn.getDate = function(format) {
var gDate = new Date();
var mDate = {
'S': gDate.getSeconds(),
'M': gDate.getMinutes(),
'H': gDate.getHours(),
'd': gDate.getDate(),
'm': gDate.getMonth() + 1,
'y': gDate.getFullYear(),
}
// Apply format and add leading zeroes
return format.replace(/([SMHdmy])/g, function(key){return (mDate[key] < 10 ? '0' : '') + mDate[key];});
return getDate(str);
};
})( jQuery );
// Usage: example #1. Write to '#date' div
$('#date').html($().getDate("y-m-d H:M:S"));
// Usage: ex2. Simple clock. Write to '#clock' div
function clock(){
$('#clock').html($().getDate("H:M:S, m/d/y"))
}
clock();
setInterval(clock, 1000); // One second
// Usage: ex3. Simple clock 2. Write to '#clock2' div
function clock2(){
var format = 'H:M:S'; // Date format
var updateInterval = 1000; // 1 second
var clock2Div = $('#clock2'); // Get div
var currentTime = $().getDate(format); // Get time
clock2Div.html(currentTime); // Write to div
setTimeout(clock2, updateInterval); // Set timer 1 second
}
// Run clock2
clock2();
// Just for fun
// Usage: ex4. Simple clock 3. Write to '#clock3' span
function clock3(){
var formatHM = 'H:M:'; // Hours, minutes
var formatS = 'S'; // Seconds
var updateInterval = 1000; // 1 second
var clock3SpanHM = $('#clock3HM'); // Get span HM
var clock3SpanS = $('#clock3S'); // Get span S
var currentHM = $().getDate(formatHM); // Get time H:M
var currentS = $().getDate(formatS); // Get seconds
clock3SpanHM.html(currentHM); // Write to div
clock3SpanS.fadeOut(1000).html(currentS).fadeIn(1); // Write to span
setTimeout(clock3, updateInterval); // Set timer 1 second
}
// Run clock2
clock3();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<div id="date"></div><br>
<div id="clock"></div><br>
<span id="clock3HM"></span><span id="clock3S"></span>
Enjoy!
You could make use of this snippet
$('.datepicker').datepicker({
changeMonth: true,
changeYear: true,
yearRange: '1900:+0',
defaultDate: '01 JAN 1900',
buttonImage: "http://www.theplazaclub.com/club/images/calendar/outlook_calendar.gif",
dateFormat: 'dd/mm/yy',
onSelect: function() {
$('#datepicker').val($(this).datepicker({
dateFormat: 'dd/mm/yy'
}).val());
}
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
selector: <input type="text" class="datepicker">
</p>
<p>
output: <input type="text" id="datepicker">
</p>
Simply we can format the date like,
var month = date.getMonth() + 1;
var day = date.getDate();
var date1 = (('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + date.getFullYear();
$("#txtDate").val($.datepicker.formatDate('dd/mm/yy', new Date(date1)));
Where "date" is a date in any format.
Take a look here:
https://github.com/mbitto/jquery.i18Now
This jQuery plugin helps you to format and translate date and time according to your preference.
Use dateFormat option when creating date picker.
$("#startDate").datepicker({
changeMonth: true,
changeYear: true,
showButtonPanel: true,
dateFormat: 'yy/mm/dd'
});
you can use the below code without the plugin.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script>
$( function() {
//call the function on page load
$( "#datepicker" ).datepicker();
//set the date format here
$( "#datepicker" ).datepicker("option" , "dateFormat", "dd-mm-yy");
// you also can use
// yy-mm-dd
// d M, y
// d MM, y
// DD, d MM, yy
// &apos;day&apos; d &apos;of&apos; MM &apos;in the year&apos; yy (With text - 'day' d 'of' MM 'in the year' yy)
} );
</script>
Pick the Date: <input type="text" id="datepicker">
You can try http://www.datejs.com/
$('#idInput').val( Date.parse("Jun 18, 2017 7:00:00 PM").toString('yyyy-MM-dd'));
BR
This worked for me with slight modification and without any plugin
Input : Wed Apr 11 2018 00:00:00 GMT+0000
$.date = function(orginaldate) {
var date = new Date(orginaldate);
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = month + "/" + day + "/" + year;
return date;
};
$.date('Wed Apr 11 2018 00:00:00 GMT+0000')
Output: 04/11/2018
I have achieved through this, I have resolved this without any plugin or datepicker.
GetDatePattern("MM/dd/yyyy");
function GetDatePattern(pattern)
{
var monthNames=["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
var todayDate = new Date();
var date = todayDate.getDate().toString();
var month = todayDate.getMonth().toString();
var year = todayDate.getFullYear().toString();
var formattedMonth = (todayDate.getMonth() < 10) ? "0" + month : month;
var formattedDay = (todayDate.getDate() < 10) ? "0" + date : date;
var result = "";
switch (pattern) {
case "M/d/yyyy":
formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
result = formattedMonth + '/' + formattedDay + '/' + year;
break;
case "M/d/yy":
formattedMonth = formattedMonth.indexOf("0") == 0 ? formattedMonth.substring(1, 2) : formattedMonth;
formattedDay = formattedDay.indexOf("0") == 0 ? formattedDay.substring(1, 2) : formattedDay;
result = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
break;
case "MM/dd/yy":
result = formattedMonth + '/' + formattedDay + '/' + year.substr(2);
break;
case "MM/dd/yyyy":
result = formattedMonth + '/' + formattedDay + '/' + year;
break;
case "yy/MM/dd":
result = year.substr(2) + '/' + formattedMonth + '/' + formattedDay;
break;
case "yyyy-MM-dd":
result = year + '-' + formattedMonth + '-' + formattedDay;
break;
case "dd-MMM-yy":
result = formattedDay + '-' + monthNames[todayDate.getMonth()].substr(3) + '-' + year.substr(2);
break;
case "MMMM d, yyyy":
result = todayDate.toLocaleDateString("en-us", { day: 'numeric', month: 'long', year: 'numeric' });
break;
}
}
I'm not quite sure if I'm allowed to answer a question that was asked like 2 years ago as this is my first answer on stackoverflow but, here's my solution;
If you once retrieved the date from your MySQL database, split it and then use the splitted values.
$(document).ready(function () {
var datefrommysql = $('.date-from-mysql').attr("date");
var arraydate = datefrommysql.split('.');
var yearfirstdigit = arraydate[2][2];
var yearlastdigit = arraydate[2][3];
var day = arraydate[0];
var month = arraydate[1];
$('.formatted-date').text(day + "/" + month + "/" + yearfirstdigit + yearlastdigit);
});
Here's a fiddle.
Here is the full code example I have show on browser, Hope you also helpful thanks.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker functionality</title>
<link href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!-- Javascript -->
<script>
$(function() {
$( "#datepicker" ).datepicker({
minDate: -100,
maxDate: "+0D",
dateFormat: 'yy-dd-mm',
onSelect: function(datetext){
$(this).val(datetext);
},
});
});
</script>
</head>
<body>
<!-- HTML -->
<p>Enter Date: <input type="text" id="datepicker"></p>
</body>
</html>
using Moment JS
moment js
$("#YourDateInput").val(moment($("#YourDateInput").val()).format('YYYY-MM-DD'));
u can use this coding
$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));

javascript date of specific day of the week in MM/dd/yyyy format not libraries

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));
}

Javascript days +/- from today

For a datepicker I need two dates:
from: today - 7 days,
to: today + 7 days.
I get a currentDate with:
var toDay = new Date();
var curr_date = toDay.getDate();
var curr_month = toDay.getMonth();
curr_month++;
var curr_year = toDay.getFullYear();
var toDay = (curr_month + "/" + curr_date + "/" + curr_year);
How to get 7 days+ and 7 days- dates ? With corresponding month!
As per comment, You can use following code
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
var nextWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());
myDate = new Date();
myDate.setDate(myDate.getDate() -7 );
var prevWeekDate = ((myDate.getMonth() + 1) + "/" + myDate.getDate() + "/" + myDate.getFullYear());
Modified Demo
Pretty simple:
nextWeek.setDate(toDay.getDate() + 7);
lastWeek.setDate(toDay.getDate() - 7);
Javascript saves a date as the number of milliseconds since midnight on january 1st 1970. You can get this time by calling "getTime()" on the Date object. You can then add 7X24X60X60X1000 to get 7 days later, or substract them for 7 days earlier represented in milliseconds. Then call Date.setTime() again.
edit: both these other methods involving getDate() get unpredictable when you are around the start or end of a month.
You can also extend your javascript Date object like this
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
Date.prototype.substractDays = function(days) {
this.setDate(this.getDate() - days);
return this;
};
//then
var dateDiff=7;
var toDay = new Date();
var futureDay= new Date(toDay.addDays(dateDiff));
var prevDay = new Date(toDay.substractDays(dateDiff*2)); // substracted 14 daysbecause 'toDay' value has been incresed by 7 days
Hope this helps.
You can add /subtract like following
var fdate= new Date();
var numberofdayes= 7;
fdate.setDate(fdate.getDate() + numberofdayes);
(Not sure whether you are asking that or not)
Then you can format it in dd/mm/yyyy using getDate(), getMonth() and getFullYear().
(Don't forget to add 1 to fdate.getMonth())
var formateddate = fdate.getDate()+ '/'+ fdate.getMonth()+1 + '/'+ fdate.getFullYear();

Categories

Resources