繁体   English   中英

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

[英]Set values in input type date and time in javascript

我有两个输入字段:

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

如何将这些字段设置为当前日期/时间?

您可以使用相应的格式设置输入字段的value

  • dateyyyy-MM-dd
  • timeHH:mm

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

var date = new Date();
var currentDate = date.toISOString().substring(0,10);
var currentTime = date.toISOString().substring(11,16);

document.getElementById('currentDate').value = currentDate;
document.getElementById('currentTime').value = currentTime;
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;

我发现使用 ISOString,格式当然是标准化的。 您可以简单地将字符串在 'T' 处拆分为日期和时间数组(包括祖鲁语,您可能希望拼接出最后一个字符 '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);

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

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

为了将日期转换为不带时间的 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">

这将根据当前时区返回当前日期和时间。

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

只需使用 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)

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

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 ;

你可以使用这个代码

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

并在您的脚本中编写此代码

var date = new Date();

var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();

if (month < 10) month = "0" + month;
if (day < 10) day = "0" + day;

var today = year + "-" + month + "-" + day +"T00:00";       
document.getElementById("currentDate").value = today;

如何将这些字段设置为当前日期/时间?

如果您想要本地时间(不是 UTC/GMT!)的浏览器/客户端的日期/时间,请使用

var date = new Date();
document.getElementById('currentDate').valueAsDate = date;
document.getElementById('currentTime').value = date.toTimeString().substring(0,5);

如果您想要更多的时间粒度(例如也是秒),那么在子字符串中增强“5”(例如到“8”)。 现代浏览器提供日期/时间选择器,从提供的值扩大时间输入字段,并尊重浏览器的“语言/日期-时间格式”首选项。 上述解决方案为任何浏览器的“语言/日期时间格式”首选项正确设置日期和时间(小时和分钟)。

其他解决方案的问题是:

  1. Date.toISOString()提供 UTC/Zulu 时间

  2. toLocaleTimeString可能会提供“9:12”而不是所需的“09:12”:

  3. date.toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit' })有效,但date.toTimeString().substring(0,5)更短,无需选择任何语言环境,例如“it-IT”

它就像调用下面的函数一样简单:

 var time = new Date() .toLocaleTimeString("en-US", { hour12: false }); console.log("time", time);

使用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);

暂无
暂无

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

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