JavaScript : displaying Yesterdays Date in JavaScript - javascript

I was trying to display Yesterday Date on click of the button , but why its showing Date as "2013-6-0"
instead of 2013-05-31
Could anybody please tell me what i was doing wrong
<!DOCTYPE html>
<html>
<head>
<script>
function displayDate()
{
var d = new Date();
var curr_date = d.getDate()-1;
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
var yesterday = curr_year + "-" + curr_month + "-" + curr_date ;
document.write(yesterday);
}
</script>
</head>
<body>
<p id="demo">Click Button to Display Yesterday Date</p>
<button type="button" onclick="displayDate()">Display Date</button>
</body>
</html>

You should update and then reference the date from which you've subtracted 1 day:
var d = new Date();
d.setDate(d.getDate() - 1); // <-- add this to make it "yesterday"
var curr_date = d.getDate(); // <-- don't subtract 1 anymore
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
DEMO

Your code simply takes a day number (like 1, 2, ...) and subtracts one from it. Why would you expect that to automatically roll the day back to the previous month?
You can generate new dates by subtracting milliseconds from a given date. Try this:
var today = new Date();
# subtract milliseconds representing one day from current date
var yesterday = new Date(today - 24*60*60*1000);

var today = new Date();
var yesterday = new Date();
yesterday.setDate(today.getDate()-1);
var yesterdayStr = yesterday.getFullYear() + "-" + (yesterday.getMonth()+1) + "-" + yesterday.getDate();

function displayDate()
{
var today = new Date();
today.setDate(today.getDate()-1);
var yyyy = today.getFullYear().toString();
var mm = (today.getMonth()+1).toString();
mm = mm.length==2?mm:"0"+mm;
var dd = today.getDate().toString();
dd = dd.length==2?dd:"0"+dd;
var yesterday = yyyy+"-"+mm+"-"+dd;
document.write(yesterday);
}

Related

Split Date.now() into parts in Javascript

I am trying to split the current date into parts and this is what I am doing
var today = new Date();
var currDay = today.getDay();
var currMonth = today.getMonth();
var currYear = today.getYear();
alert(currDay + "/" + currMonth + "/" + currYear)
but with this I get the following result
0/7/115 (output)
where it should be
09/07/2015
What can I do to get the required result?
Your "today.getDay()" should be "today.getDate()" since .getDay goes from 0-6 (days of the week)
var today = new Date();
var currDay = today.getDate();
var currMonth = today.getMonth();
var currYear = today.getFullYear();
alert(currDay + "/" + currMonth + "/" + currYear);
Try
var currYear = today.getFullYear();
Based on the answer from https://stackoverflow.com/a/3605248/2649340:
var today = new Date();
var output = ('0' + today.getDate()).slice(-2) + '/'
+ ('0' + (today.getMonth()+1)).slice(-2) + '/'
+ today.getFullYear();
getDay() gives you the day's number (0-6 for sunday to monday), month starts with 0 for january. This is how to do:
var today = new Date();
var day = today.getDate();
var month = today.getMonth()+1;
var year = today.getFullYear();
if(day<10) {
day='0'+day;
}
if(month<10) {
month='0'+month;
}
today = month+'/'+day+'/'+year;
alert(today);
you can use moment.js. It has a lot of helpful functions for time and date in JavaScript

Java Script Set min and max attribute for date

I want to restrict date picking beyond 7 days from the current date.. help me out
<script>
var date = new Date();
var startdate = date.getFullYear().toString()+"-"+ date.getMonth.toString()+"-"+date.getDate()+1.toString();
var maxdate =date.getFullYear().toString()+"-"+ date.getMonth.toString()+"-"+date.getDate()+6.toString();
document.getElementById("demo").setAttribute("min",startDate);
document.getElementById("demo").setAttribute("max",maxdate);
</script>
There are so many ways of doing this here's one:
var date = new Date();
var startDate = date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate();
maxDate = startDate.split('-').map(Number);
maxDate[2] += 7;
demo.max = maxDate.join('-');
demo.min = startDate;

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)

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

Get last week date with jQuery/Javascript

I'm trying to get the last week date in JavaScript, without the time.
So for example, 10-02-2012, instead of 10-02-12 13:34:56 GMT.
Is there an easy solution out there for this?
Thank you!
Edit:
I'm trying to make this dynamic, so that the resulting variable is always one week before the current date. Here's what I've done to calculate the today variable, if this helps or can be used!
var currentTime = new Date();
var month = currentTime.getMonth() + 1
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var today = month + "-" + day + "-" + year;
alert(today)
I prefer something like this
​
function getLastWeek() {
var today = new Date();
var lastWeek = new Date(today.getFullYear(), today.getMonth(), today.getDate() - 7);
return lastWeek;
}
var lastWeek = getLastWeek();
var lastWeekMonth = lastWeek.getMonth() + 1;
var lastWeekDay = lastWeek.getDate();
var lastWeekYear = lastWeek.getFullYear();
var lastWeekDisplay = lastWeekMonth + "/" + lastWeekDay + "/" + lastWeekYear;
var lastWeekDisplayPadded = ("00" + lastWeekMonth.toString()).slice(-2) + "/" + ("00" + lastWeekDay.toString()).slice(-2) + "/" + ("0000" + lastWeekYear.toString()).slice(-4);
console.log(lastWeekDisplay);
console.log(lastWeekDisplayPadded);
And if you're using jQuery UI, you can do this instead of the manual steps to build the string
var lastWeekDisplay = $.datepicker.formatDate('mm/dd/yy', getLastWeek());
Or for today
var todayDisplay = $.datepicker.formatDate('mm/dd/yy', new Date());
var firstDay = new Date("2009/10/02");
var previousweek= new Date(firstDay.getTime() - 7 * 24 * 60 * 60 * 1000);
Check out this link. It will help:- http://code.google.com/p/datejs/
We can't have a javascript date question answered without mentioning Moment.js.
moment().subtract('days', 7).format('MM-DD-YYYY')
Possible without external dependencies
new Date().setDate(new Date().getDate() - 7)
If you really want to create this from a full timestamp like 10-02-12 13:34:56 GMT, you might want to do this:
var time = '10-02-12 13:34:56 GMT';
document.write(time.substr(0,7));
use this code to subtract any number of days as i have selected 9 it will give last 10 days result including today
var date = new Date();
var day=date.getDate();
var month=date.getMonth() + 1;
var year=date.getFullYear();
var startDate=day+"/"+month+"/"+year;
var dayBeforeNineDays=moment().subtract(9, 'days').format('DD/MM/YYYY');
startDate=dayBeforeNineDays;
var endDate=day+"/"+month+"/"+year;
function getLastWeek() {
let today = new Date();
let day = today.getDay();
let t = day-1;
let monday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 7); //monday from last week
let sunday = new Date(today.getFullYear(), today.getMonth(), today.getDate() - t - 1); //sunday from ast week
return [monday, sunday];
}
var last_week = getLastWeek();

Categories

Resources