Convert an input type time, to a timestamp for firestore

Viewed 373

Convert an input type time, to a timestamp for firestore

<input type="time" class="form-control job-field" id="starttime" name="starttimeadd" placeholder="Job Start Time" required>

This is what I have tried but no luck, I did have a couple of results trying a different method but that showed an invalid date or NaN.

var starttimestamp = moment.utc(moment("#starttimeadd")).format();

This is the expected result

enter image description here

This is my code

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

}
2 Answers

moment takes a date as a parameter, not an element ID like you're trying to do here. How about:

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

Also worth considering that you may not need to use Moment for this - the official docs recommend reading an article on why you may not need Moment

Close enough. Using Intl.DateTimeFormat (no 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);
}

Browser compatibility: Chrome, Edge, Firefox, IE11+

Related