I've been tasked with making an input where the user can input days and hh:mm:ss in one field as dd:hh:mm:ss, but going through the Moment.js docs such a format doesn't appear to exist. Is there a way for me to make my own workaround?
Update:
I found a way to format the string exactly how I want using duration: moment.duration( days + '.' + hours + ':' + minutes + ':' + sec).format('dd HH:mm:ss'));
(it's ugly but I can fix this part later, what matters is it works).
I created the element to be displayed in html using:
const input = document.createElement('input'); input.setAttribute('data-inputmask', '"alias": "datetime", "placeholder": "_", "inputFormat": "dd HH:MM:ss"'); input.value = value;
This produces an input value that looks like this: 01 00:00:00
, however when I try to erase the date field ( 01
), it cycles back to the last day of the previous month.
I need the result to be __ 00:00:00
( _
is my placeholder for empty values in the field) or I need to remove the ability to erase that field when the date is at 01
Update 2:
It seems like I can achieve the desired result by using input.setAttribute('data-inputmask', '"alias": "datetime", "placeholder": "_", "inputFormat": "yy HH:MM:ss"');
, but is there a more elegant way of setting the inputFormat attribute? I don't want to use yy
to set my day value.
You can manipulate the tokens that moment.js provides to display time and date as you desire like for your case:
moment().format("dddd, h:mm:ss");
I have linked the displaying portion of the docs you can find more ways there as well. More Info here
You'll need to handle the days 'manual';
After the input was altered;
.add(n, 'days')
// 12 days from now @ 13:30:00 console.log(format('12:13:30:00')); // 120 days from now @ 12:11:11 console.log(format('120:12:11:11')); // -1 days (yesterday) @ 10:00:00 console.log(format('-1:10:00:00')); function format(input) { // Get number of days let days = input.substr(0, input.indexOf(':')); // Create momentjs let mom = new moment(input.replace(days, ''), 'HH:mm:SS') // Add days mom.add(days, 'days'); // Return human readable return mom.format('lll'); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Provide your custom format as the second parameter ( format ) to create an momentjs
object based on your user format. momentjs
String + Format ;
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.