[英]Convert an input type time, to a timestamp for firestore
将输入类型时间转换为 firestore 的时间戳
<input type="time" class="form-control job-field" id="starttime" name="starttimeadd" placeholder="Job Start Time" required>
这是我尝试过但没有运气的方法,我确实有一些尝试不同方法的结果,但显示日期或 NaN 无效。
var starttimestamp = moment.utc(moment("#starttimeadd")).format();
这是预期的结果
这是我的代码
function addJob(){
var starttimeadd = $('#starttimeadd').val();
const starttimestamp = moment.utc(moment(starttimeadd)).format();
db.collection("jobs").doc().set({
starttime: starttimestamp,
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
moment
将日期作为参数,而不是像您在这里尝试做的元素 ID。 怎么样:
const startTimeAdd = document.getElementById("starttimeadd").value;
const starttimestamp = moment.utc(startTimeAdd).format();
同样值得考虑的是,您可能不需要为此使用 Moment - 官方文档建议阅读一篇关于为什么您可能不需要 Moment 的文章
足够近。 使用Intl.DateTimeFormat (没有momentjs)
//code assumes that you have validated the input var startTime = "01:00"; // document.querySelector("#starttime").value; var formattedStartDateFromTime = getFormattedDateFromTime(startTime); console.log(formattedStartDateFromTime); function getFormattedDateFromTime(time) { var timeParts = time.split(":"); var startDate = new Date(); startDate.setHours(+timeParts[0]); startDate.setMinutes(+timeParts[1]); startDate.setSeconds(0); var options = { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', timeZoneName: 'short' }; return new Intl.DateTimeFormat('en', options).format(startDate); }
浏览器兼容性:Chrome、Edge、Firefox、IE11+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.