简体   繁体   English

在Java脚本中向日期添加变量号

[英]Add a variable number to a date in Java script

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. 到目前为止,我已经将代码包装到一个函数中,以便可以使用onclick方法调用它。 What should this code look like to work properly? 这段代码看起来应该如何正常工作? Almost forgot - to make life hard my date is written like this YYYY-MM-DD 差点忘了-使生活变得艰难我的约会是这样写的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. 使用Linus的建议,我进行了以下更改,但是在返回日期格式方面遇到了麻烦。 eg Setting the reservation date to 2015-01-03 gave me the result of 2015-0-32 for the return date 例如,将预订日期设置为2015-01-03,则返回日期为2015-0-32

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. 如前所述,使用js处理日期可能有些棘手。 But to just add days to a date this could be a solution? 但是,仅将日期添加几天,这可能是一个解决方案?

JSBIN: http://jsbin.com/lebonababi/1/edit?js,output JSBIN: http ://jsbin.com/lebonababi/1/edit?js,输出

JS: 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,它与原始代码更加一致。

JSBin: http://jsbin.com/guguzoxuyi/1/edit?js,output JSBin: http ://jsbin.com/guguzoxuyi/1/edit? js,输出

HTML: 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: 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;

}

Example using todays date: 使用今天的日期的示例:

var today = new Date();
today.setDate(today.getDate() + x);

where x is the number of days. 其中x是天数。 Then just use getYear(), getMonth() and getDate() and format it how you like. 然后只需使用getYear(),getMonth()和getDate()并按照自己的喜好对其进行格式化。

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 假设您的日期以dd / mm / yyyy格式作为inputDate输入,然后

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. 根据日期格式,您的split()分隔符和数组位置可能会有所不同,但这是通常的想法。

As per my comment, 根据我的评论,

Split reservation_begin and use the Date constructor feeding in the parts to create a Javascript date object. 拆分 reservation_begin并使用Date构造函数填充各部分以创建Javascript日期对象。 getTime will give you the milliseconds since the Epoch. getTime将为您提供自纪元以来的毫秒数。 There are 86400000 milliseconds in a day, so multiply this by loan_period . 一天有86400000毫秒,因此请乘以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. 将两个毫秒结果相加,然后将Date构造函数与总毫秒数一起使用,以将dateResult作为Javascript日期对象获得。

using Date.UTC but you don't have to. 使用Date.UTC,但您不必这样做。

 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. 这是用Javascript Date表示的最小值,使用它可以避免浏览器中可能出现的任何翻转问题。

Why use UTC? 为什么要使用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. 您不必使用它,只需将零件输入Date并使用非UTC get方法即可。

What does pad do? pad做什么? It formats the month values to MM and date values to DD. 它将月份值格式化为MM,将日期值格式化为DD。

Note that month is zero referenced in Javascript so months are represent by the numbers 0-11. 请注意,在Javascript中,月份是零,因此月份由数字0-11表示。

A bit confused with the third variable "reservation_end" but according to your question this solution might work. 与第三个变量“ reservation_end”有些混淆,但是根据您的问题,此解决方案可能有效。 var dateResult = new Date(reservation_begin); dateResult.setDate(dateResult.getDate() + parseInt(loan_period)); alert(dateResult);

http://jsfiddle.net/uwfpbzt2/ http://jsfiddle.net/uwfpbzt2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM