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()
Related
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();
}
whenever I'm defining the timeframe being in German session language after changing to English lang. session (and vice versa) I'm getting the:
java.text.ParseException: Unparseable date: "10.10.2018"
Here is the fragment:
Date startDateFormatted = DateUtils.convertDateToMinusDayNumber(cal, dayRange);
Date endDateFormatted = new Date();
if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate))
{
try
{
String datePattern = getLocalizedString("dd.MM.yyyy"); //
startDateFormatted = new SimpleDateFormat(datePattern).parse(startDate); // exception is throwing on this line
endDateFormatted = new SimpleDateFormat(datePattern).parse(endDate);
}
catch (final Exception e)
{
LOG.error(ERROR_DATE_PARSING, e);
}
}
java.time
I recommend you use java.time, the modern Java date and time API, for your date work.
String datePattern = "dd.MM.uuuu";
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(datePattern);
String startDateString = "10.10.2018";
LocalDate startDate = LocalDate.parse(startDateString, dateFormatter);
System.out.println(startDate);
Output:
2018-10-10
If you want to support different date formats for different locales, let Java handle that part for you:
String datePattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.MEDIUM, null, IsoChronology.INSTANCE, Locale.GERMAN);
German locale works with your example string of 10.10.2018. For UK locale, for example, a string like 10 Oct 2018 would be required instead, as Britons would typically expect.
What went wrong in your code?
We cannot tell from the information and code that you have provided exactly what happened. A couple of good guesses are:
As Arvind Kumar Avinash said in a comment, getLocalizedString() may be causing trouble. You may print datePattern to check. Localization is something you do to strings that you display to the user. Trying to localize a format pattern string for a formatter is probably plain wrong, so you should leave out that method call. That the error occurs when changing language seems to support this possibility.
There may be unexpected non-printing characters in your string. One way to check would be to print startDate.length(). If the length is greater than 10, there are more characters than the 10 chars in 10.10.2018.
Link
Oracle tutorial: Date Time explaining how to use java.time.
Quite simply, this is my code:
http://jsfiddle.net/NibblyPig/k9zb4ysp/
moment.locale('en-GB');
var d = moment('22/12/2019');
alert(d);
I would expect this to parse, however it says invalid date.
I have referenced moment.js and the locale/en-gb.js
I'm writing a global control so the date may come in in a variety of formats.
If I put in a variety of American dates they all work, for example 12/12/2019, 12/12/2019 23:04 etc.
However the locale command does not appear to do anything and I cannot get a single date to parse. What am I doing wrong?
You need to pass the format as the second argument for moment(), as discussed here:
moment.locale('en-GB');
var d = moment('22/12/2019', 'DD/MM/YYYY');
alert(d);
https://jsfiddle.net/a4gu6kfz/
From the docs:
If you know the format of an input string, you can use that to parse a
moment.
moment("12-25-1995", "MM-DD-YYYY");
I think that there is no need to write your own complex logic to parse your input, you can use moment(String, String) (or moment(String, String[], String, Boolean)), as suggested by Thales Minussi's answer.
moment(String) is the good choice only if your input is in ISO 8601 or RFC 2822 compliant form.
In your case, you can probably use Localized formats listed in the format section of the docs. If you have a list of possible formats, I think that the best choice is tho use moment(String, String[]).
Please note that, by default: Moment's parser is very forgiving, so using default Forgiving Mode will handle "any" character as separator.
Here a live sample:
moment.locale('en-GB');
['22/12/2019', '22/12/2019 15:00',
'22-12-2019', '22-12-2019 15:00',
'1-3-2019', '1-12-2019', '22-1-2019'
].forEach((elem) => {
var d = moment(elem, 'L LT');
console.log(d.format());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/en-gb.js"></script>
Still hoping there's a nice moment js way to do this but in the meantime I just bashed this together. Pretty nasty and it will probably go wrong in 80 years or so.
http://jsfiddle.net/NibblyPig/k9zb4ysp/22/
var a = "23/03/19 12:42:21.123";
var datePart = a.substring(0, a.indexOf(" "));
var timePart = a.substring(a.indexOf(" ") + 1);
var dateParts = datePart.split("/");
if (dateParts[0].length == 1) dateParts[0] = "0" + dateParts[0];
if (dateParts[1].length == 1) dateParts[1] = "0" + dateParts[1];
if (dateParts[2].length == 2) {
var threshold = parseInt(new Date().getFullYear().toString().substring(2)) + 10;
if (parseFloat(dateParts[2]) > threshold ) {
dateParts[2] = "19" + dateParts[2];
}
else
{
dateParts[2] = "20" + dateParts[2];
}
}
alert (parseFloat(dateParts[2] + dateParts[1] + dateParts[0] + timePart.replace(/:/g, "").replace(/\./g, "")));
This won't solve every usecase, but in your specific example if you want just a simple date (with no time component) auto-parsed in UK format you can just use the 'L' format string having set the locale to 'en-GB'
Your example with this change (your jsfiddle also)
moment.locale('en-GB');
// just pass 'L' i.e. local date format as a parsing format here
var d = moment('22/12/2019', 'L');
alert(d);
It's quite nice because you get the auto parsing of various formats you wanted for free. For instance this works just the same:
var d = moment('22-12-2019', 'L');
You can return a date using moment.js in a desired format -
return moment(aDateVar).format('DD/MM/YYYY');
I have a unix timestamp that I am trying to convert to the local timezone and then to render the .fromNow. However I can't seem to find the best way to convert to the local timezone and the current formatting technique cannot be used with .fromNow. Can someone point out what I am doing wrong with the formatting and how I can get the local timezone of the user?
Unix Example:
1541032289
Attempt:
moment(1541032289).format('YYYY MM DD').fromNow();
Error Message:
TypeError: moment(...).format(...).fromNow is not a function
UPDATE:
Code after replacing .format() with .unix()
Code:
store.zrevrange(zrangeSet, 0, -1, function(err, keys){
var range = [];
for (var i = 0; i < keys.length; i ++ ) {
var keyObj = JSON.parse(keys[i]);
keyObj.timestamp = moment().unix(keyObj.timestamp).fromNow();
range.push(keyObj);
}
console.log(range);
});
New Error:
keyObj.timestamp = moment().unix(keyObj.timestamp).fromNow();
^
TypeError: moment(...).unix(...).fromNow is not a function
There are two issues in your code. First, format returns a string while you should invoke fromNow() on moment objects. So, you can simply remove format('YYYY MM DD').
The second issue is that you have to use moment.unix(Number) instead of moment(Number).
As the documentation states:
To create a moment from a Unix timestamp (seconds since the Unix Epoch), use moment.unix(Number).
Here a live sample:
console.log( moment.unix(1541032289).fromNow() );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
On both examples I'm giving it a String like the following: 26-03-17
Dim mvarValor As String
Dim dateVarValor As DateTime
This code snippet is throwing an exception on the TryParse:
If Not mvarValor = Nothing AndAlso DateTime.TryParse(mvarValor, dateVarValor) Then
Return Format(dateVarValor, mvarFormat)
Else
Return strNull
End If
The next code snippet is not throwing an exception, but a False like it should:
DateTime.TryParse(mvarValor, dateVarValor)
If dateVarValor = Nothing Then
Return strNull
Else
Return Format(dateVarValor, mvarFormat)
End If
Why is the first code snippet giving me an exception?
Thanks in advance!
DateTime.TryParse throws three types of exceptions
http://msdn.microsoft.com/en-us/library/9h21f14e(v=vs.100).aspx
you must be getting one of those. Here is the proper usage of DateTime.TryParse
var culture = CultureInfo.CreateSpecificCulture("en-US");
string parsedDateTime = null;
if (DateTime.TryParse(parseMe, culture, DateTimeStyles.None, out dateResult))
{
parsedDateTime = dateResult;
}
this snippet will parse the datetime without throwing an exception.
I hope this helps :)
You need to pass in a Y2K compliant date. The parser can't tell the year from 2 digits. If you pass 2003-12-25 it will validate that the date does in fact exist, but 03-12-25 is ambiguous.