How to check if a string denotes a 24 hour valid time format using momentJS? - momentjs

The code:-
moment(moment("2022-12-12").format("YYYY-MM-DD"), "YYYY-MM-DD", true).isValid()
returns true as 2022-12-12 is a valid date in YYYY-MM-DD format.
Using the same logic, I tried to check if var timeString = "16:00:00" is a valid time or not.
However, the following code:-
moment(moment("16:00:00").format("HH:mm:ss"), "HH:mm:ss", true).isValid()
always gives me false.
What am I doing wrong?

It's always giving true as you are formatting to that particular type first than checking if its valid which is why its always true.
I think you want something like this.
function isTimeFormat(time) {
return moment(time, 'HH:mm:ss', true).isValid();
}

Related

Check if date valid using moment and format 'YYYY-MM-DDThh:mm:ss.SSS+ss:ss' does not work

I'm trying to check if a string YYYY-MM-DDThh:mm:ss.SSS+ss:ss
But I always get false.
For example:
const value = '2022-02-16T22:23:53.000+00:00'
moment(value, DATE_FORMAT, true).isValid();
Please advise, am I using the wrong format ?
Date format should have been - YYYY-MM-DDTHH:mm:ss.SSSZ

how to handle deprecation warning in momentjs

I want to use momentjs to check for invalid date/time strings:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
This (correctly) throws a stacktrace with the familiar 'Deprecation warning: value provided is not in a recognized RFC2822 or ISO format......'
But even if I add a try/catch:
try {
var invalid = '2017-03-18 23;00;00';
if (moment(invalid).isValid()) {
return 'valid date'
}
catch (err) {
throw Error ('invalid date format');
}
the stacktrace is still printed.
What do I need to do to avoid the stacktrace from being printed?
I've searched all similar questions on StackOverflow but they all try to solve a different problem (fixing the input or finding the correct syntax to parse the input).
I using v2.18.1.
You have to use moment(String, String); to parse your input. If you don't want to specify a format (or an array of formats), you can use moment.ISO_8601. As the docs says:
Moment already supports parsing iso-8601 strings, but this can be specified explicitly in the format/list of formats when constructing a moment
This way you will not have deprecation warning. Here a working example:
var invalid = '2017-03-18 23;00;00';
if (moment(invalid, moment.ISO_8601).isValid()) {
console.log('valid date');
} else {
console.log('invalid date');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
PS. Anyway, if you have a list of accepted format, I suggest to use moment(String, String[]); (and strict parsing, if needed).
Specify the string format for your date then the warning will go away
moment("2017-1-27", 'YYYY-M-D').format('DD MMMM YYYY')
Below works for me to remove RFC2822 warnings
Use moment(String, FormatString) to convert string to date.
var newDt = Moment(this.state.dob,"MM/DD/YY")
And below code from date to String
var dt = Moment(newDt).format("YYYY-MM-DD")
By this way it will not show warning messages.
Adding .format() without any arguments to the moment expression that was causing that warning was the solution for me:
moment(r.created_at.toDate()).format()

Drop timezone before format

I want to add one second to random time in ISO format, e.g.
var t = "2015-01-13T00:00:00+11:00";
moment(t).add(1, "second").format(); // expected "2015-01-13T00:00:01+11:00", but get "2015-01-12T18:00:01+05:00"
So it converts t to current browser timezone (+05:00 in my case) and only then adds a second.
How can I drop timezone before adding and return it after?
I found:
moment.parseZone(t).add("1", "second").format(); // "2015-01-13T00:00:01+11:00"

Why am I getting and invalid QDateTime object?

My code looks like this
std::string date = "04/05/2015 02:07";
std::string format = "MM/dd/yyyy HH:mm";
QDateTime dateTime = QDateTime::fromString(date.c_str(), format.c_str());
bool isItValid = dateTime.isValid();
This is part of a function I have but I narrowed the problem to specifically that value for date. After executing, isItValid is false. Why is it not a valid date?
However, if I try
bool isItValid = dateTime.date().isValid() && dateTime.time().isValid();
the value is true.
Can anyone point out what's the problem with that date? what am I missing?
The documentatation of isValid() (http://doc.qt.io/qt-5/qdatetime.html#isValid) says:
Returns true if both the date and the time are valid and they are
valid in the current Qt::TimeSpec, otherwise returns false.
If the timeSpec() is Qt::LocalTime or Qt::TimeZone then the date and
time are checked to see if they fall in the Standard Time to Daylight
Time transition hour, i.e. if the transition is at 2am and the clock
goes forward to 3am then the time from 02:00:00 to 02:59:59.999 is
considered to be invalid.
So it seems it's the Qt::TimeSpec you are missing.

Issue in converting Timespan variable to 12 hour format

I have a nullable variable Start time
Timespan? st=e.StartTime;//Null-able variable;
I am trying to get time in AM/PM format but I am unable to get it.
DateTime date = Convert.ToDateTime(st.ToString());
String f = String.Format("{0:hh:mm:tt}", date);
Error is:
System.FormatException: String was not recognized as a valid DateTime.
If you were to output the results of st.ToString(), you will find that it doesn't contain any date information, only hours, minutes and seconds.
This isn't a valid format for a DateTime, which generally contain date and time information.
You don't need to convert your TimeSpan to a DateTime to format it, you can just use TimeSpan.ToString():
string f = st.Value.ToString(#"hh\:mm\:tt");
For reference: http://msdn.microsoft.com/en-us/library/ee372287.aspx
Also, note the \ before the :, you must do this if you want to include literal strings in the output, as mentioned at the bottom of that documentation page.
Converting a timespan to a date is not possible, a timespan represents x amount of minutes/hours/whatever and you cannot get an exact date from that alone. If you have a date as a starting point, you can add a timespan and that will give you the new date.
st.ToString() will return "System.Nullable<Timespan>" because that is what a nullable type returns - it does not override the default Object.ToString implementation, so returns the type name.
If you want the string of the actual timespan, then you would need to do st.Value.ToString(), but you should be checking for null first (i.e. st.HasValue == true)
Edit: Also see #Sean's comment about how to output the Timespan without converting to a DateTime first.
Edit: Turns out I was slightly wrong - st.ToString() doesn't return the above. So see Sean's answer.
First convert Timespan to Datetime by adding TimeSpan to a base date of 00:00 hrs. Then on that dateTime derive the 12 hr format.
DateTime.Now.Date.Add(OpenTimeSpan).ToString(#"hh\:mm\:tt")
The Accepted Answer is wrong.
You cannot return AM/PM for a TimeSpan because it is only concerned with the length of Time,
not a Time of Day - hench the name, "TimeSpan".
Convert to a DateTime first before converting to a String:
string sTimeOfDay = new DateTime().Add(st).ToString("hh:mm tt");
Note: If your TimeSpan is nullable, then you will need to add Conditional Logic to Handle Nulls and pass in ts.Value instead of ts:
string sTimeOfDay = (st == null ? null : new DateTime().Add(st.value).ToString("hh:mm tt") );

Resources