I use momentjs to work with date and time
let dateAndTime = moment(component.props.data.value, moment.ISO_8601);
let date = '',
time = '';
if (dateAndTime) {
if (moment(dateAndTime, 'YYYY-MM-DD', true).isValid()) {
date = moment(dateAndTime).format('YYYY-MM-DD');
}
if (moment(dateAndTime, 'HH:mm', true).isValid()) {
time = moment(dateAndTime).format('HH:mm');
}
}
this code works just fine if component.props.data.value
contains date and time like 2018-05-22 14:45
or if it contains only date like 2018-05-22
. The problem is sometimes component.props.data.value
contains only time like 14:45
, so moment(component.props.data.value, moment.ISO_8601)
doesn't create moment object and code below doesn't execute. Is there any way to handle case only for time?
js is a JavaScript package that makes it simple to parse, validate, manipulate, and display date/time in JavaScript. Moment. js allows you to display dates in a human-readable format based on your location.
There will be no new features, no changes to the API, and the complaints about the library (especially its performance) won't be addressed. It also means that, with time, Moment will gradually become obsolete and unsuited for modern apps.
Moment.js is a Swiss Army knife for working with dates in JavaScript. It allows you to parse, validate, manipulate, and display dates and times using a clean and concise API. In this article I’ll show you how to get up and running with Moment.js, as well as demonstrate several of its common use cases.
We initiate a new Node application. We install Moment.js with npm i moment command. In the first example, we get today's date with Moment.js. The example prints today's date and time. We load the Moment.js library.
Moment.js datetime arithmetic The add () function is used to add date and time to the moment object and the subtract () function subtract date and time from the moment object.
Another annoying task that Moment.js has greatly simplified is date validation. In order to perform validation, simply pass a date string to the moment object, along with the desired date format, and call the isValid () method. This will return true if the date is valid, and false otherwise.
You can use moment(String, String[])
, as the docs says:
If you don't know the exact format of an input string, but know it could be one of many, you can use an array of formats.
This is the same as String + Format, only it will try to match the input to multiple formats.
Your first line of code could be like the following:
let dateAndTime = moment(component.props.data.value, [moment.ISO_8601, 'HH:mm']);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With