简体   繁体   English

如何从html输入类型时间创建javascript日期对象?

[英]How to create javascript date object from html input type time?

This question answers how to convert HH:mm:ss string into a Javascript date object. 这个问题回答了如何将HH:mm:ss字符串转换为Javascript日期对象。 The string returned from HTML time input is not always in the HH:mm:ss format. 从HTML时间输入返回的字符串并不总是采用HH:mm:ss格式。 The format varies. 格式各不相同。

The answers in the linked question will not work in-case of dynamic formats. 链接问题中的答案不适用于动态格式。

How to create a Javascript date object from this input value which does not have a fixed format? 如何从此输入值(不具有固定格式)创建Javascript日期对象?

I assume you want current date, in that case you need to get the current date and then pass the current time. 我假设您想要当前日期,在这种情况下,您需要获取当前日期,然后传递当前时间。

 var today = new Date(); var dd = String(today.getDate()).padStart(2, '0'); var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0! var yyyy = today.getFullYear(); today = mm + '/' + dd + '/' + yyyy; console.log(new Date(today + " " + "13:30" /*pass your time*/)); 

This is an optimised version of benihamalu 's answer . 这是benihamalu 答案的优化版本。

 const today = new Date(); console.log(new Date(today.toDateString() + ' ' + "13:30")); 

simple answer 简单的答案

 function TimeToDate(time) { var today = new Date(); time = new Date('1970-01-01' + ' ' + time + 'Z').getTime(); var date = today.setHours(0, 0, 0, 0); var DateTime = new Date(date + time); return DateTime; } console.log(TimeToDate("13:30:7.026")); 

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

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