简体   繁体   中英

How to use moment.js to format the v-model data from a vuetify v-text-field (type:time)?

I have this element:

<v-text-field
  label="Choose a time"
  type="time"
  mask="time"
  step="1800"
  prepend-inner-icon="access_time"
  v-model="expiryTime"
  :rules="[v => !!v || 'Time is required']"
  required
  @change="getTime"
></v-text-field>

I want to trigger the getTime method to convert the v-model value into a h:mm format. As I've been testing I have entered 12:00 pm each time as the value for expiryTime and have done the following:

getTime(){
  alert(moment().format('h:mm')) //returns current time in x:xx format
  alert(this.expiryTime); // Returns '1200'
  alert(moment(this.expiryTime).format('h:mm')); // returns '4:26, expect 12:00
  alert(moment(this.expiryTime, 'h:mm')); // returns 'Sat Aug 17 2019 12:00:00 GMT-0600', expect 12:00

Basically I'm getting some unexpected values and I don't know why. If I can get the current time in the top alert I am rather confused about how formatting the expiryTime data the same ways ends up being 4:26 . And the final alert returns the entire time with the date and etc.

Can someone please explain how I can convert the expiryTime data to be in h:mm format properly?

The moment(String) constructor takes either a ISO 8601 string, or an RFC2822 date time string . If neither of those standards are used, the format must be specified as the second argument of the constructor.

expiryTime ( 1200 ) is in the form of hmm , but you had specified h:mm , which would've required a colon between the hour and minutes for moment to parse the date correctly. The fix is to remove the colon.

 console.log(moment(1200, 'hmm').format('h:mm')) console.log(moment(135, 'hmm').format('h:mm')) console.log(moment(2001, 'hmm').format('h:mm')) 
 <script src="https://unpkg.com/moment@2.24.0/moment.js"></script> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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