在javascript中设置输入类型日期和时间的值

时间:2015-02-25 21:09:22

标签: javascript html html5

我有2个输入字段:

日期:

<input type="date" id="currentDate">

时间:

<input type="time" id="currentTime" >

我正在测试html5的这些新功能。 如何在这些字段中设置当前值。 我很难通过javascript在这些字段中设置值。

9 个答案:

答案 0 :(得分:13)

您只需使用相应的格式设置输入字段的value

dateyyyy-MM-dd

timeHH:mm

使用您的示例,您可以执行以下操作:

var date = new Date();
var currentDate = date.toISOString().slice(0,10);
var currentTime = date.getHours() + ':' + date.getMinutes();

document.getElementById('currentDate').value = currentDate;
document.getElementById('currentTime').value = currentTime;

答案 1 :(得分:2)

var date = new Date();

var day = date.getDate(),
    month = date.getMonth() + 1,
    year = date.getFullYear(),
    hour = date.getHours(),
    min  = date.getMinutes();

month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;

var today = year + "-" + month + "-" + day,
    displayTime = hour + ":" + min; 

document.getElementById('formdate').value = today;      
document.getElementById("formtime").value = displayTime;

答案 2 :(得分:1)

var date = new Date();
var dateOptions = { day: '2-digit', month: '2-digit', year: 'numeric' };
var currentDate = date.toLocaleDateString('ja-JP', dateOptions).replace(/\//gi, '-');
var timeOptions = { hour: '2-digit', minute: '2-digit' };
var currentTime = date.toLocaleTimeString('it-IT', timeOptions);

document.getElementById('currentDate').value = currentDate;
document.getElementById('currentTime').value = currentTime;

答案 3 :(得分:1)

为了将日期转换为没有时间的ISO日期,您需要使用getDategetMonth等方法,而不是直接获取ISOString并对其进行操作。串。后者不会考虑时区,这将导致意外结果。

这是使用ES6的解决方案。

// Function which returns a minimum of two digits in case the value is less than 10
const getTwoDigits = (value) => value < 10 ? `0${value}` : value;

const formatDate = (date) => {
  const day = getTwoDigits(date.getDate());
  const month = getTwoDigits(date.getMonth() + 1); // add 1 since getMonth returns 0-11 for the months
  const year = date.getFullYear();

  return `${year}-${month}-${day}`;
}

const formatTime = (date) => {
  const hours = getTwoDigits(date.getHours());
  const mins = getTwoDigits(date.getMinutes());

  return `${hours}:${mins}`;
}

const date = new Date();
document.getElementById('currentDate').value = formatDate(date);
document.getElementById('currentTime').value = formatTime(date);
<input type="date" id="currentDate">
<input type="time" id="currentTime">

现在,它将按照当前时区返回当前日期和时间。

答案 4 :(得分:0)

使用jquery:

var date  = new Date(), // The Date object lets you work with dates.
    year  = date.getFullYear(), // This method gets the four digit year.
    month = date.getMonth() + 1, // This method gets the month and Jan is 0.
    day   = date.getDate(), // This method gets the day of month as a number.
    hour  = date.getHours(), // This method gets the hour 
    min   = date.getMinutes(); // This method gets the minutes
month = (month < 10 ? '0' + month : month);
day   = (day   < 10 ? '0' + day   : day  ); 
hour  = (hour  < 10 ? '0' + hour  : hour ); // It adds a 0 to number less than 10 because input[type=time] only accepts 00:00 format. 
min   = (min   < 10 ? '0' + min   : min  );

$('#currentDate').val(day + '/' + month + '/' + year); // This line sets the value.
$('#currentTime').val(hour + ':' + min);

答案 5 :(得分:0)

我发现使用ISOString可以毫无疑问地将格式标准化。您只需在字符串“ T”处分割日期和时间数组即可(包括Zulu,您可能希望拼接出最后一个字符“ Z”)。

因此,我找到的最简单的解决方案仅仅是:

let tmp = new Date(Date.now());

// tmp now like: "2018-08-21T11:54:50.580Z"

let dateInputFormatted = tmp.toISOString().split('T')[0];

// 0, as split produces: ["2018-08-21", "11:54:50.580Z"]

console.log(dateInputFormatted);

答案 6 :(得分:0)

您可以制作两个原型以便重复使用:

    Date.prototype.dateToInput = function(){
        return this.getFullYear() + '-' + ('0' + (this.getMonth() + 1)).substr(-2,2) + '-' + ('0' + this.getDate()).substr(-2,2);
    }
    Date.prototype.timeToInput = function(){
        return  ('0' + (this.getHours())).substr(-2,2) + ':' + ('0' + this.getMinutes()).substr(-2,2);
    }

然后像这样使用它们:

    var date = new Date();
    document.getElementById('currentDate').value = date.dateToInput();
    document.getElementById('currentTime').value = date.timeToInput();

答案 7 :(得分:0)

在现代浏览器上,这非常简单:

仅使用HTML_element .valueAsDate 而不是HTML_element .value

// just my preference to access form elements by names
const myForm = document.querySelector('#my-Form')

// 1: get local date and time values
let sysDate  = new Date()  
  , userDate = new Date(Date.UTC(sysDate.getFullYear(), sysDate.getMonth(), sysDate.getDate(),  sysDate.getHours(), sysDate.getMinutes(), 0));

// 2: set interface values !
myForm.currentDate.valueAsDate = userDate
myForm.currentTime.valueAsDate = userDate
<form action="xxx" id="my-Form">

  <input type="date" name="currentDate">
  <br><br>
  <input type="time" name="currentTime">

</form>

currentTime元素的秒和毫秒信息必须设置为零

userDate.setSeconds(0)
userDate.setMilliseconds(0)

答案 8 :(得分:0)

假设您有任何文本格式的日期(文本)值。

Eg. myDate = 28-08-2020;

现在,要在<input type="date"/>上进行设置,您需要以“ YYYY-MM-DD”格式携带日期。

所以

var tempD = date.split("-");
myDate = tempD[2] + "-" + tempD[1] + "-" + tempD[0]; //myDate will be = 2020-08-28
document.getElementById("myDate").value = myDate ;