"reset date value in Javascript"? - javascript

How to "reset date value in Javascript" everytime the div in html is clicked? I am trying to make a basic delivery calculation date based from today's date, for example, 3 days delivery date from today(let say today is 5 November 2011). When user click on it, it must show the delivery date will be on Tuesday 8 November 2011, but when user click on it again, the second time, today's date has changed to be based on 8 November 2011 instead of 5. How to reset/clear the "Today" variable to be based on today's date?
How to display day in Monday, Tuesday, Wednesday, and so on instead of 1,2,3,4,5,6,7?
My current code is
$(document).ready(function() {
var Today = new Date();
var NumDelivery = 0;
function Calculate() {
var days = Today.getDay();
var dd = Today.getDate();
var mm = Today.getMonth() + 1;
var y = Today.getFullYear();
var FormattedDate = days + ',' + dd + '-'+ mm + '-'+ y;
Today.setDate(Today.getDate() + NumDelivery);
$('#DateDelivery').text(FormattedDate);
}

Umm, how about simply use NewDate = new Date() and then instead of Today.setDate(...) use NewDate.setDate(...)
As for day names you can use an array like this :
var d = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
dayName = d[NewDate.getDay()];

Just move the var Today = new Date() into the function Calculate
$(document).ready(function() {
var NumDelivery = 0;
var DAYS_OF_WEEK = [ 'Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat' ];
function Calculate() {
var Today = new Date();
var days = Today.getDay();
var dd = Today.getDate();
var mm = Today.getMonth() + 1;
var y = Today.getFullYear();
var FormattedDate = DAYS_OF_WEEK[days] + ',' + dd + '-'+ mm + '-'+ y;
Today.setDate(Today.getDate() + NumDelivery);
$('#DateDelivery').text(FormattedDate);
}
I displayed the day of week name using an array.

Related

How would I fix this function to change month depending on the date?

I'm trying to create a function that creates a dynamic date range based on the date supplied in a string.
What I've done so far:
Capture date in the string I'm looking to change;
Check to see if that date is a Thursday (if so the range will need to account for the weekend)
What I need to do:
Find a way to get the second date in the range to account for the weekend;
Find a way to make sure that the second date takes into account the last day of the month.
Apologies for old syntax, GTM doesn't like anything using ES6 so I'm a little constrained on this project.
Note I am using DD/MM/YYYY
var regex = /[\d\/\d\/\d]/g;
var text = document.querySelector('.shipmentLineTitle b');
var originalDate = text.innerText.match(regex, "");
if (originalDate.length > 10) {
originalDate.pop();
originalDate.join('');
}
var ogDateString = originalDate.join('');
var dayNumber = originalDate.splice(0, 2).join('');
var monthNumber = originalDate.splice(1, 2).join('');
var yearNumber = originalDate.splice(2, 4).join('');
// if originalDate is a thursday (5) dynamicString will need to be a Monday (1).
var date = new Date(yearNumber, monthNumber -1, dayNumber);
var dynamicDateString = "";
if (date.getDay == 5) {
var newDate = new Date(date) + (86400000 * 3);
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dymamicDateString = dd + '/' + mm + '/' + yy;
} else {
var newDate = new Date(date) + 86400000;
var dd = newDate.getDate();
var mm = newDate.getMonth() +1;
var yy = newDate.getFullYear();
dynamicDateString = dd + '/' + mm + '/' + yy;
}
var newContent = 'Delivery will be made between ' + ogDateString + ' - ' + dynamicDateString + '. An accurate delivery date will be provided after you place your order.';
text.innerText = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 09/10/2020 (1 delivery)</b></span>
Thursday is day 4
Here is a simpler script
var textField = document.querySelector('.shipmentLineTitle b'),
text = textField.innerText,
originalDate = text.match(/\d{2}\/\d{2}\/\d{4}/)[0].split("/"),
dayNumber = +originalDate[0],
monthNumber = +originalDate[1],
yearNumber = +originalDate[2],
date = new Date(yearNumber, monthNumber - 1, dayNumber, 15, 0, 0, 0),
aDay = 86400000,
newDate = new Date(date),
day = date.getDay(),
daysToAdd = 1; // Sunday to Wednesday
// if originalDate is a Thursday (4) or Saturday (6), dynamicString will need to be a Monday (1).
if (day === 4) daysToAdd = 4; // Thursday - delivery Monday
else if (day === 6) daysToAdd = 2; // Saturday
newDate.setDate(newDate.getDate() + daysToAdd);
var dd = newDate.getDate(),
mm = newDate.getMonth() + 1,
yy = newDate.getFullYear(),
dynamicDateString = dd + '/' + mm + '/' + yy,
newContent = text + ' - ' + dynamicDateString + '</b>. An accurate delivery date will be provided after you place your order.';
textField.innerHTML = newContent;
<span class="shipmentLineTitle">Delivery details: <b>your delivery will arrive on 08/10/2020 (1 delivery)</b></span>
I would suggest to user moment.js a very good date library to manipulate dates. It has lot of function to add/substract dates, hours, days etc.
There is https://www.npmjs.com/package/moment-business-days which servers exactly what you need

How can i convert seconds into date format in Javascript

The code is as below my Start_DateVal has the selected date and from the datepicker .And i am trying to alert the date which is 8 months ahead from the selected date (Start_DateVal).
function ChangeEndDate()
{
var Start_DateVal = document.getElementById("Start_Date").value;
if(Start_DateVal!='')
{
var arr=Start_DateVal.split("-");
var day= arr[0];
var month= arr[1];
var year= arr[2];
var d = new Date(year, month, day);
var InSeconds=d.setMonth(d.getMonth() + 8);
alert(InSeconds); //Here i wanted to display in date format instead of seconds.
}
}
Problem Statement: i am getting the alert in Seconds (InSeconds) Variable .But how do i convert Seconds into DD-MM-YYYY Date Format.Please Help me Thank you.
var d = new Date(2017, 01, 12);
var date = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if(date<10){
date='0'+date;
}
if(month<10){
month='0'+month;
}
alert(date + '-' + month + '-' + year)

Adding additional days but only on a Weekday (Mon-Fri) and skipping the weekend

How can the function below be modified such that if getdate('add',2) was called and that if the present date was to land on a Friday ie. (Feb. 23, 2015) the additional 2 "work week" dates would bring the new "work week" date to Feb. 27, 2015.
I need the function to basically skip the weekend. If the present date lands on Friday.
function getdate(type,y) {
if (type == 'add') {
var someDate = new Date();
var numberOfDaysToAdd = y
someDate.setDate(someDate.getDate() + numberOfDaysToAdd);
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var yyyy = someDate.getFullYear();
return dd + '/'+ mm + '/'+ yyyy
}
}
I use while to check if every next day is weekend day or not,if yes then skip it.
function getdate(type,y) {
if (type == 'add') {
var someDate = new Date();
var numberOfDaysToAdd = y;
var i=1;
while(i<=numberOfDaysToAdd){
someDate.setDate(someDate.getDate() + 1);
if(someDate.getDay() != 0 && someDate.getDay() != 6){//if the day isn't weekend days,then count it.
i++;
}
}
var dd = someDate.getDate();
var mm = someDate.getMonth() + 1;
var yyyy = someDate.getFullYear();
return dd + '/'+ mm + '/'+ yyyy
}
}
so this code you can skip all weekend days even if the added date is next 2 or more weeks.

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

validate a dropdown list to get proper date based on the option selected

- I have a dropdown List on which there are some options from which user can select one.
- Options are 1 day, 1 week, 2 weeks, 1 month and 6 months
- Now when I select option 1 day, today's date should be incremented by one and next date is shown.
- If I select 1 week, the date falling after one week should be shown.
- Now the problem is when I select an option it sometimes shows date greater than 30/31.
- I use below javacript function:
function select_duration(ddlcupon) {
var skillsSelect = document.getElementById("ddlcupon");
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
if (selectedText == "1 Day") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 1;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Week") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 7;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "2 Weeks") {
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate() + 14;
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "1 Month") {
var currentTime = new Date();
var month = currentTime.getMonth() + 2;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
if (selectedText == "6 Months") {
var currentTime = new Date();
var month = currentTime.getMonth() + 7;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var exdate = month + "/" + day + "/" + year;
document.getElementById('<%=txtEventDate.ClientID%>').value = exdate.toString();
}
- Can someone help me in getting a proper date?
try using this
var dt1 = new Date();
var dt2 = new Date(dt1.getTime() + (86400000 * numberOfDay) );
if your date is incremented by one day try
var dt2 = new Date(dt1.getTime() + (86400000 * 1 ) ); //so on
The problem is you're incrementing day, month and year. So, if the month is 12, you'll get 13. You could work directly with milliseconds. For example:
var d = new Date('01/31/2013'); // Thu Jan 31 2013 00:00:00 GMT-0200 (BRST)
var addDay = 1000 * 60 * 60 * 24;
var currentMs = d.getTime();
d.setTime(currentMs + addDay);
console.log(d); // Fri Feb 01 2013 00:00:00 GMT-0200 (BRST)
Date.js is a handy script for all kinds of JavaScript date manipulation.
The syntax to add n number of days to current day is
// Add 3 days to Today
Date.today().add(3).days();
In this case adds 3 days to the current date.

Categories

Resources