【问题标题】:Convert an input type time, to a timestamp for firestore将输入类型时间转换为 Firestore 的时间戳
【发布时间】:2021-01-23 12:32:32
【问题描述】:

将输入类型时间转换为 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);
});

}

【问题讨论】:

  • 您预期的时间戳输出是多少?
  • 您需要输入的值,而不是 html 元素。此外,将它传递给 moment 会给你一个 moment 对象。您可能想节省纪元时间。
  • $('#starttimeadd').val()。字符串中的值是什么
  • @naveen 01:00 同上,是使用html5输入时间

标签: javascript html firebase google-cloud-firestore


【解决方案1】:

足够接近。使用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+

【讨论】:

    【解决方案2】:

    moment 将日期作为参数,而不是像您在此处尝试那样的元素 ID。怎么样:

    const startTimeAdd = document.getElementById("starttimeadd").value;
    const starttimestamp = moment.utc(startTimeAdd).format();
    

    另外值得考虑的是,您可能不需要为此使用 Moment - 官方文档建议阅读 why you may not need Moment 上的文章

    【讨论】:

    • 这不起作用,现在它在控制台中显示无效的时间值
    猜你喜欢
    • 1970-01-01
    • 2021-01-18
    • 2013-02-14
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多