Add a variable number to a date in Java script - javascript

I have read a few articles but nothing seems to the point. I have created a form that records a reservation date (when a user wants to reserve a game) and the number of days they hope to borrow it for. I want to add this to the reservation date to get the date the game must be returned by. I have wrapped up my code so far into a function so that I can call it using an onclick method. What should this code look like to work properly? Almost forgot - to make life hard my date is written like this YYYY-MM-DD
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var reservation_end = document.getElementById('return_date');
var dateResult = reservation_begin + loan_period;
return_date.value = dateResult;
}
USING the Suggestions made by Linus
I made the following alterations but had trouble with the formatting of the return date. e.g Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date
function ReturnDate(){
var reservation_begin = document.getElementById('reservation_start').value;
var loan_period = document.getElementById('requested_days').value;
var resDate = new Date(reservation_begin);
alert(resDate)
var period = loan_period;
var output = document.getElementById('return_date');
resDate.setDate(resDate.getDate() + period);
alert(period)
//return_date.value = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
return_date.value = resDate.getFullYear() + "-" + resDate.getMonth() + "-" + (resDate.getDate() +1);
}

As mentioned dates could be a bit tricky to handle with js.
But to just add days to a date this could be a solution?
JSBIN: http://jsbin.com/lebonababi/1/edit?js,output
JS:
var resDate = new Date('2015-02-01');
var period = 6;
var output = "";
resDate.setDate(resDate.getDate() + period);
output = resDate.getFullYear() + "-" + (resDate.getMonth() + 1) + "-" + resDate.getDate();
alert(output);
EDIT:
Added a new JSBin which is more consistent with the original code.
JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output
HTML:
<input id="reservationStart" type="text" value="2015-03-01" />
<br />
<input id="requestedDays" type="text" value="14" />
<br />
<a id="calculateDate" href="javascript:;">Calculate Date</a>
<br /><br /><br />
Output:
<input id="calculatedDate" type="text" />
JS:
// Click event
document.getElementById('calculateDate').addEventListener('click', returnDate);
// Click function
function returnDate(){
var reservationStart = document.getElementById('reservationStart').value,
requestedDays = parseInt(document.getElementById('requestedDays').value),
targetDate = new Date(reservationStart),
formattedDate = "";
// Calculate date
targetDate.setDate(targetDate.getDate() + requestedDays);
// Format date
formattedDate = formatDate(targetDate);
// Output date
document.getElementById('calculatedDate').value = formattedDate;
}
// Format date (XXXX-XX-XX)
function formatDate(fullDate) {
var dateYear = fullDate.getFullYear(),
dateMonth = fullDate.getMonth()+1,
dateDays = fullDate.getDate();
// Pad month and days
dateMonth = pad(dateMonth);
dateDays = pad(dateDays);
return dateYear + "-" + dateMonth + "-" + dateDays;
}
// Pad number
function pad(num) {
return (num < 10 ? '0' : '') + num;
}

As per my comment,
Split reservation_begin and use the Date constructor feeding in the
parts to create a Javascript date object. getTime will give you the
milliseconds since the Epoch. There are 86400000 milliseconds in a day, so
multiply this by loan_period. Add the two millisecond result together
and use the Date constructor with your total milliseconds to get
dateResult as a Javascript date object.
using Date.UTC but you don't have to.
function pad(num) {
return num < 10 ? '0' + num : num;
}
var reservation_begin = ('2015-02-01').split('-'),
loan_period = '5',
begin,
end;
reservation_begin[1] -= 1;
begin = new Date(Date.UTC.apply(null, reservation_begin)).getTime();
end = new Date(begin + 86400000 * loan_period);
document.body.textContent = [
end.getUTCFullYear(),
pad(end.getUTCMonth() + 1),
pad(end.getUTCDate())
].join('-');
Why split the date string into parts? This is to avoid cross browser parsing issues.
Why use milliseconds? This is the smallest value represented by Javascript Date, using this will avoid any rollover issues that may be present in browsers.
Why use UTC? You haven't specified the requirements for your script, and this is about as complex as it gets. You don't have to use it, you can just feed the parts into Date and use the non UTC get methods.
What does pad do? It formats the month values to MM and date values to DD.
Note that month is zero referenced in Javascript so months are represent by the numbers 0-11.

A bit confused with the third variable "reservation_end" but according to your question this solution might work.
var dateResult = new Date(reservation_begin);
dateResult.setDate(dateResult.getDate() + parseInt(loan_period));
alert(dateResult);
http://jsfiddle.net/uwfpbzt2/

Example using todays date:
var today = new Date();
today.setDate(today.getDate() + x);
where x is the number of days. Then just use getYear(), getMonth() and getDate() and format it how you like.
EDIT
var myDate = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Assuming your date is entered in dd/mm/yyyy format as inputDate then
dateParts = inputDate.split("/");
var myDate = new Date(dateParts[2], dateParts[1]-1, dateParts[0]);
Depending on the date format your split() delimiter and array positions may be different but this is the general idea.

Related

How to loop between dates that are in dmy format

Here is my 2 date
var startdate = '11-12-2016';
var stopdate = '13-12-2016';
I want to loop between these two dates. So, i did like this
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
while(startMedicine <= stopMedicine){
console.log(startdate)
}
But i am getting unlimited loops running in browser.
How can i do this.
Note :
I don't want to use jQuery for this one.
If the start and end date is same it should loop only once and the input date will be always d/m/y format. What is the mistake in my code. Pls help
Update :
I have mistaken the date format, my date format is d-m-y. How can i do this for one..
Increment date by one day per iteration using getDate
startdateArr = startdate.split('-');
stopdateArr = stopdate.split('-');
var startMedicine = new Date(startdateArr[2],startdateArr[1]-1,startdateArr[0]);
var stopMedicine = new Date(stopdateArr[2],stopdateArr[1]-1,stopdateArr[0]);
// thanks RobG for correcting on month index
while(startMedicine <= stopMedicine){
var v = startMedicine.getDate() + '-' + (startMedicine.getMonth() + 1) + '-' + startMedicine.getFullYear();
console.log(v);
startMedicine.setDate(startMedicine.getDate()+1);
}
In js month indexing starts at 0 so nov is 10 dec. is 11 and like so that's why i use getMonth() + 1
`
main problem is that you are not increasing your date.
here is the solution
var startdate = '11/12/2016';
var stopdate = '11/13/2016';
var startMedicine = new Date(startdate);
var stopMedicine = new Date(stopdate);
var currentMedicine = startMedicine;
var dayCount = 0;
while(currentMedicine < stopMedicine){
currentMedicine.setDate(startMedicine.getDate() + dayCount);
// You can replace '/' to '-' this if you want to have dd-mm-yyyy instead of dd/mm/yyy
var currentDate = currentMedicine.getDate() + '/' + (currentMedicine.getMonth() + 1) + '/' + currentMedicine.getFullYear(); // in dd/mm/yyyy format
console.log(currentDate);
dayCount++;
}
You can make use of moment js and moment js duration. Its for duration purpose only. It very easy and meant for same.

Date object returns NaN when trying to calculate time between two dates in IE8

I have a string which represents the expiry of an item like so: 2020-10-31T21:30:11, and I have a function to calculate the amount of days left until this date (below).
However, in IE8 it doesn't work. I think this is because timeEnd is returning NaN. Can someone explain why this doesn't work and point me in the right direction?
I have a jsFiddle here.
And here's a snippet of my code:
HTML
<span class="days-left" data-publishend="2020-10-31T21:30:11"></span>
JS
$('.days-left').each(function () {
if ($(this).data("publishend")) {
var timeEnd = new Date($(this).data("publishend")), // returns NaN in IE8
timeNow = new Date(),
oneDay = 24*60*60*1000,
oneHour = 60*60*1000,
oneMin = 60*1000,
daysLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneDay),
hoursLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneHour),
minsLeft = Math.floor(Math.abs(timeEnd.getTime() - timeNow.getTime()) / oneMin),
string;
if (daysLeft < 1) {
if (hoursLeft < 1.5) {
string = minsLeft + ' minutes';
} else {
string = hoursLeft + ' hours left';
}
}
if (daysLeft === 1) string = '1 day left';
if (daysLeft > 1) string = daysLeft + ' days left';
$(this).text(string);
}
});
You are right, IE8 won't parse your date right at the beginning (timeEnd init).
Here is the reason : https://stackoverflow.com/a/17593482/2143734
Just one more date handling issue ;)
try this
function parseISO8601(dateStringInRange) {
var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
date = new Date(NaN), month,
parts = isoExp.exec(dateStringInRange);
if(parts) {
month = +parts[2];
date.setFullYear(parts[1], month - 1, parts[3]);
if(month != date.getMonth() + 1) {
date.setTime(NaN);
}
}
return date;
}
to make the conversion.
Source: Date constructor returns NaN in IE, but works in Firefox and Chrome
From looking at answers in this Stackoverflow question, I've got a grasp of what was going on and created my own function that worked the string that I wanted to convert a date object.
IE8 cannot parse the string 2020-10-31T21:30:11 like other browsers can. But the date object can accept comma separated values representing the year, month, day, etc, and use them to create the new instance (more info about the Date object).
So I created a function that takes my string, spits it at the "T" and then splits the remaining values at either the "-" or the ":". The function then returns the a date object instance using these values as the parameters.
function parseDateString(dateString) {
var a = dateString.split('T'),
year = a[0].split('-')[0],
month = a[0].split('-')[1],
day = a[0].split('-')[2],
hour = a[1].split(':')[0],
min = a[1].split(':')[1];
return new Date(year, month - 1, day, hour, min);
}

Function to convert timestamp to human date in javascript [duplicate]

This question already has answers here:
Convert a Unix timestamp to time in JavaScript
(34 answers)
How do I format a date in JavaScript?
(68 answers)
Closed last year.
How to convert this timestamp 1382086394000 to 2013-10-18 08:53:14 using a function in javascript? Currently I have this function:
function cleanDate(d) {return new Date(+d.replace(/\/Date\((\d+)\)\//, '$1'));}
The value 1382086394000 is probably a time value, which is the number of milliseconds since 1970-01-01T00:00:00Z. You can use it to create an ECMAScript Date object using the Date constructor:
var d = new Date(1382086394000);
How you convert that into something readable is up to you. Simply sending it to output should call the internal (and entirely implementation dependent) toString method* that usually prints the equivalent system time in a human readable form, e.g.
Fri Oct 18 2013 18:53:14 GMT+1000 (EST)
In ES5 there are some other built-in formatting options:
toDateString
toTimeString
toLocaleString
and so on. Note that most are implementation dependent and will be different in different browsers. If you want the same format across all browsers, you'll need to format the date yourself, e.g.:
alert(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear());
* The format of Date.prototype.toString has been standardised in ECMAScript 2018. It might be a while before it's ubiquitous across all implementations, but at least the more common browsers support it now.
This works fine. Checked in chrome browser:
var theDate = new Date(timeStamp_value * 1000);
dateString = theDate.toGMTString();
alert(dateString );
why not simply
new Date (timestamp);
A date is a date, the formatting of it is a different matter.
Moment.js can convert unix timestamps into any custom format
In this case : var time = moment(1382086394000).format("DD-MM-YYYY h:mm:ss");
will print 18-10-2013 11:53:14;
Here's a plunker that demonstrates this.
Here are the simple ways to every date format confusions:
for current date:
var current_date=new Date();
to get the Timestamp of current date:
var timestamp=new Date().getTime();
to convert a particular Date into Timestamp:
var timestamp_formation=new Date('mm/dd/yyyy').getTime();
to convert timestamp into Date:
var timestamp=new Date('02/10/2016').getTime();
var todate=new Date(timestamp).getDate();
var tomonth=new Date(timestamp).getMonth()+1;
var toyear=new Date(timestamp).getFullYear();
var original_date=tomonth+'/'+todate+'/'+toyear;
OUTPUT:
02/10/2016
we need to create new function using JavaScript.
function unixTime(unixtime) {
var u = new Date(unixtime*1000);
return u.getUTCFullYear() +
'-' + ('0' + u.getUTCMonth()).slice(-2) +
'-' + ('0' + u.getUTCDate()).slice(-2) +
' ' + ('0' + u.getUTCHours()).slice(-2) +
':' + ('0' + u.getUTCMinutes()).slice(-2) +
':' + ('0' + u.getUTCSeconds()).slice(-2) +
'.' + (u.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5)
};
console.log(unixTime(1370001284))
2016-04-30 08:36:26.000
This is what I did for the Instagram API. converted timestamp with date method by multiplying by 1000.
and then added all entity individually like (year, months, etc)
created the custom month list name and mapped it with getMonth() method which returns the index of the month.
convertStampDate(unixtimestamp){
// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];
// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);
// Year
var year = date.getFullYear();
// Month
var month = months_arr[date.getMonth()];
// Day
var day = date.getDate();
// Hours
var hours = date.getHours();
// Minutes
var minutes = "0" + date.getMinutes();
// Seconds
var seconds = "0" + date.getSeconds();
// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
// final date
var convdataTime = month+' '+day;
return convdataTime;
}
Call with stamp argument
convertStampDate('1382086394000')
and that's it.
Use .toLocaleString:
// undefined uses default locale
console.log(new Date().toLocaleString(undefined, {dateStyle: 'short'}));
Or custom method in case you don't want to use the toLocaleString for some reason:
formatDate is the function you can call it and pass the date you want to format to dd/mm/yyyy
var unformatedDate = new Date("2017-08-10 18:30:00");
$("#hello").append(formatDate(unformatedDate));
function formatDate(nowDate) {
return nowDate.getDate() +"/"+ (nowDate.getMonth() + 1) + '/'+ nowDate.getFullYear();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hello">
</div>
My ES6 variant produces a string like this 2020-04-05_16:39:45.85725. Feel free to modify the return statement to get the format that you need:
const getDateStringServ = timestamp => {
const plus0 = num => `0${num.toString()}`.slice(-2)
const d = new Date(timestamp)
const year = d.getFullYear()
const monthTmp = d.getMonth() + 1
const month = plus0(monthTmp)
const date = plus0(d.getDate())
const hour = plus0(d.getHours())
const minute = plus0(d.getMinutes())
const second = plus0(d.getSeconds())
const rest = timestamp.toString().slice(-5)
return `${year}-${month}-${date}_${hour}:${minute}:${second}.${rest}`
}
There is a simple way to convert to a more readable form
new Date().toLocaleString();
new Date(1630734254000).toLocaleString();
Outputs in this format => 9/4/2021, 11:14:14 AM
new Date(timestamp).toString().substring(4, 15)
1631685556789 ==> Sep 15 2021
To calculate date in timestamp from the given date
//To get the timestamp date from normal date: In format - 1560105000000
//input date can be in format : "2019-06-09T18:30:00.000Z"
this.calculateDateInTimestamp = function (inputDate) {
var date = new Date(inputDate);
return date.getTime();
}
output : 1560018600000

How to parse date string in jQuery and check if it is in the past

I need to check if the date is in the past. This is what I have so far. JSfiddle here.
var date = "09/12/2013";
var d = new Date();
var month = d.getMonth() + 1;
var day = d.getDate();
var todaysDate = +(('' + day).length < 2 ? '0' : '') + day + '/' + (('' + month).length < 2 ? '0' : '') + month + '/' + d.getFullYear();
if (date < todaysDate) {
alert("in the past");
} else {
alert("in the future");
}
Currently it is saying that the date was in the past, when it should be in the future. I know I need to parse the string as a date, but not sure how.
Help?
With that input format, you can't use a string comparison, because the least significant values are on the left. Note: I'm assuing that date is December 9th, 2013. If you're doing the American thing where it's September 12th, 2013, you'll have to adjust the indexes into parts below.
You could reverse the fields:
var date = "09/12/2013";
var parts = date.split('/');
date = parts[2] + "/" + parts[1] + "/" + parts[0];
...and then do your string comparison (being sure to construct the string for "today" in the same order — year/month/day).
If you're going to do that, you could go ahead and finish the job
var date = "09/12/2013";
var parts = date.split('/');
var date = new Date(parseInt(parts[2], 10), // year
parseInt(parts[1], 10) - 1, // month, starts with 0
parseInt(parts[0], 10)); // day
if (date < new Date()) {
// It's in the past, including one millisecond ago
}
...but of course, if you don't want the expression to be true for one millisecond ago, your string approach is fine.
var date = new Date("09/12/2013");
var d = new Date();
console.log(date>d); // true
var date = new Date("09/12/2011");
console.log(date>d); // false
JavaScript's native Date comparator only works on Date objects, whereas you are comparing Strings. You should parse date into a Date object, and then compare it with d.
//define parse(string) --> Date
if(parse(date) < new Date()) {
alert('past');
} else {
alert('future');
}

Javascript DateDiff

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.
Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?
//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";
//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);
//Try this function...
function DateDiff(date1, date2) {
return date1.getTime() - date2.getTime();
}
//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).
EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!
//Set the two dates
var currentTime = new Date()
var currDate = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.
//currDate = 8/17/12 and iniPastedDate = 8/7/12
function DateDiff(date1, date2) {
var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value
}
//Write out the returning value should be using this example equal -10 which means
//it has passed by ten days. If its positive the date is coming +10.
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
Your first try does addition first and then subtraction. You cannot subtract strings anyway, so that yields NaN.
The second trry has no closing ). Apart from that, you're calling getTime on strings. You'd need to use new Date(...).getTime(). Note that you get the result in milliseconds when subtracting dates. You could format that by taking out full days/hours/etc.
function setDateWeek(setDay){
var d = new Date();
d.setDate(d.getDate() - setDay); // <-- add this
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1;
var curr_year = d.getFullYear();
return curr_date + "-" + curr_month + "-" + curr_year;
}
setDateWeek(1);
No need to include JQuery or any other third party library.
Specify your input date format in title tag.
HTML:
< script type="text/javascript" src="http://services.iperfect.net/js/IP_generalLib.js">
Use javascript function:
IP_dateDiff(strDate1,strDate2,strDateFormat,debug[true/false])
alert(IP_dateDiff('11-12-2014','12-12-2014','DD-MM-YYYY',false));
IP_dateDiff function will return number of days.

Categories