Javascript: wrong date calculation - javascript

So I just have posted a question about this code (which was answered):
$(document).ready(Main);
function Main() {
ConfigDate();
}
function ConfigDate() {
var currentTime = new Date();
var dayofWeek = currentTime.getDay();
var daysSinceThursday = (dayofWeek + 3) % 7
var lastThursday = new Date(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
$("#last_thursday").text(yyyy + " / " + mm + " / " + dd);
}
The problem now is that the date that appears in my cell is 1969 / 12 / 31 (which isn't even a thursday).
Did I do something wrong while calculating last thursday date?

This is because .getDate() returns the day of the month. So you are building your date based on a serial number of something less than 30, which won't even set your seconds above 1.
Use .setDate() instead of building a new date:
date.setDate(date.getDate() - daysSinceThursday);
.setDate() will modify your existing date object, it doesn't return a new date.

You're trying to set a Date based only on the day of the month of the last Thursday. Try something like this:
var daysSinceThursday = (dayofWeek + 3) % 7;
var lastThursday = new Date(currentTime.getTime());
lastThursday.setDate(currentTime.getDate() - daysSinceThursday);
var dd = lastThursday.getDate();
var mm = lastThursday.getMonth() + 1;
var yyyy = lastThursday.getFullYear();
http://jsfiddle.net/rAuRF/3/

Related

Current Date converted to 10 days before and 10 days after

I have this code where I convert the current date to this format 2020-08-20 . But how do I alter it to give me the date 10 days from today and 10 days before today.
eg today is 2020-08-20 I am trying to get 10 days from today 2020-08-30
This is my code
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
console.log(dateConverter(today));
It's a little bit tricky. First set the hours from the date to 12 for avoiding problems with summer/wintertime-changing. Then use getDate add 10 for the extra days and setDate with the new value. Now you have a value in milliseconds, generate out of this a new date to get an dateobject. For the second date subtract 20 days because the original date was changed by the action before and do all other the same.
Format the output for the dates with getFullYear, getMonth and getDate
. Because month is handled in JS from 0 to 11 add 1 month. Months and days could be 1-digit but you want it 2 digits, so add before the string "0" and get the last 2 chars of it with slice.
Do the format for both dates and return them as array.
const dateConverter = (dateIn) => {
dateIn.setHours(12);
let dateIn10days = new Date(dateIn.setDate(dateIn.getDate() + 10));
let dateFor10days = new Date(dateIn.setDate(dateIn.getDate() - 20));
let strIn10Days = dateIn10days.getFullYear() + '-' + ('0' +(dateIn10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateIn10days.getDate()).slice(-2);
let strFor10Days = dateFor10days.getFullYear() + '-' + ('0' +(dateFor10days.getMonth()+1)).slice(-2) + '-' + ('0' + dateFor10days.getDate()).slice(-2);
return [strFor10Days, strIn10Days];
}
let today = new Date();
console.log(dateConverter(today));
Try this
const dateConverter = (dateIn) => {
var year = dateIn.getFullYear();
var month = dateIn.getMonth() + 1; // getMonth() is zero-based
var day = dateIn.getDate();
return year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
var today = new Date();
var numberOfDaysToAdd = 10;
var tenDaysPlus = today.setDate(today.getDate() + numberOfDaysToAdd);
console.log(dateConverter(today));
var today = new Date();
var numberOfDaysToSubtract = 10;
var tenDaysMinus = today.setDate(today.getDate() - numberOfDaysToSubtract);
console.log(dateConverter(today));
I would suggest you to use the moment library but you still want plain javascript
const convert = (date) => {
const pastDate = new Date(date)
pastDate.setDate(pastDate.getDate() - 10);
const futureDate = new Date(date)
futureDate.setDate(futureDate.getDate() + 10);
return { pastDate, futureDate }
}
call convert function with any date.
This code will help you
Reference JavaScript calculating date from today date to 7 days before
for after 10 days just just convert the - to +
const dateConverter = (dateIn) => {
var dates ={};
var days = 10; // Days you want to subtract
for(let i=0;i<days;i++){
var date = dateIn;
var last = new Date(date.getTime() - (i * 24 * 60 * 60 * 1000));
var day = last.getDate();
var month= last.getMonth()+1;
var year= last.getFullYear();
dates[i] = year + "-" + month.toString().padStart(2, "0") + "-" + day.toString().padStart(2, "0");
}
return dates
}
var today = new Date();
console.log(dateConverter(today));
I've been messing around that before as well.
But on this Stack Overflow you can find a really good answer:
Add days to JavaScript Date
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = new Date();
alert(date.addDays(5));
This is the code taken from that post.
For subtracting days, just replace the "+ days" with "- days"
Hope this solved your problem!
You can convert all the dates to timestamp and then simply calculate with them:
const dateTimestamp = new Date("2020-10-10").getTime()
const milisecondsInADay = 60*60*24*1000
const milisecondsInTenDays = milisecondsInADay * 10
const beforeDate = new Date(dateTimestamp - milisecondsInTenDays)
const afterDate = new Date(dateTimestamp + milisecondsInTenDays)
console.log("before", beforeDate)
console.log("after", afterDate)
console.log("initially", new Date(dateTimestamp))

How can I use input type date to dynamically only allow for one year from current date?

Here is my code so far. I am not sure how to accomplish a max date other than setting that in the input tag itself. I want it to be dynamic so whatever the current date is, the calendar only allows a selection of up to one year.
<input type="date" id="txtDate" />
$(function(){
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if(month < 10)
month = '0' + month.toString();
if(day < 10)
day = '0' + day.toString();
var maxDate = dtToday + 365;
alert(maxDate);
$('#txtDate').attr('max', maxDate);
});
example: today is 10/1/2019 it should be allowed to only select dated from 10/1/2019-10/1/2020 tomorrow a user should be allowed to only select from 10/2/2019-10/2/2020
link to fiddle
Setting the min and max values for a date input based on today's date can be done when the page loads:
// Formt date as YYYY-MM-DD
function formatISOLocal(d) {
let z = n => ('0' + n).slice(-2);
return d.getFullYear()+'-'+z(d.getMonth()+1) + '-' + z(d.getDate());
}
window.onload = function() {
let inp = document.querySelector('#i0');
let d = new Date();
inp.min = formatISOLocal(d);
inp.defaultValue = inp.min;
d.setFullYear(d.getFullYear() + 1);
inp.max = formatISOLocal(d);
// Debug
console.log(inp.outerHTML);
}
<input type="date" id="i0">
If the user agent doesn't support input type date, this will still set the min/max/default values, but you'll have to handle out of range values yourself.
Just add a year to the current date
var dtToday = new Date();
dtToday.setYear(dtToday.getYear() + 1);
$(function(){
var dtToday = new Date();
dtToday.setFullYear(dtToday.getFullYear() + 1)
let formatted_date = dtToday.getFullYear() + "-" + (dtToday.getMonth() + 1) + "-" + dtToday.getDate()
alert(formatted_date);
$('#txtDate').attr('max', formatted_date);
});
You can't add to a date object like that; you need to first get it as a timestamp. You can do that by using Date.now() or, if you need the Date object, dtToday.getTime().
That gives you a timestamp in milliseconds, so you also need to convert 365 days into milliseconds; meaning you want to add 365 * 24 * 60 * 60 * 1000 to it, not just 365.

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

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

Compare two dates in JS

I want to compare the user's birthday against today's date and get the number of days in between. The birthday they enter will be in the form of 12/02/1987 in an input box of type text
In my JS file I have code that looks like this:
function validateDOB(element) {
var valid = false;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //do that January is NOT represented by 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
var today = mm + '/' + dd + '/' + yyyy;
alert(today);
if (element.value != today) {
var days = 0;
var difference = 0;
Christmas = new Date("December 25, 2011");
today = new Date();
difference = today - Christmas
days = Math.round(difference / (1000 * 60 * 60 * 24)-1);
alert(days);
valid = true;
}
Instead of using "Christmas" I want to compare element.value... how do I do this?
When I put difference = today - element.value it won't show me the difference. The alert box comes up as NaN.
I wrote a lightweight date library called Moment.js to handle stuff like this.
var birthday = moment('12/02/1987', 'MM-DD-YYYY');
var inputDate = moment(element.value, 'MM-DD-YYYY');
var diff = birthday.diff(inputDate, 'days');
http://momentjs.com/docs/#/displaying/difference/
You'll need to first parse element.value as a date:
difference = today - new Date(element.value);
http://jsfiddle.net/gilly3/3DKfy/

Categories

Resources