GWT - Date Validation - gwt

can anyone tell me how to do date validation in GWT please. im passing date as String. it should to be converted to date format and its format is to be validated.

import com.google.gwt.i18n.client.DateTimeFormat;
...
DateTimeFormat myDateTimeFormat = DateTimeFormat.getFormat(...);
Date date = myDateTimeFormat.parseStrict(dateString);
parseStrict() throws an IllegalArgumentException for invalid date strings.

You can use GWT Bean Validation pattern matching expression for String:
#Pattern( regexp = "some javascript regular expression" )
private String dateStr;
or this when you have date:
#DateTimeFormat(pattern = "dd.MM.yy")
private Date myStartDate;
I do not use this but you can see a complete sample in gwt-2.5.0 samples directory.
Have a nice time.

Related

Extract the date format from react-intl

I have a component that uses a datepicker. The datepicker needs a dateFormat property that fits the momentjs pattern, for example 'DD.MM.YYYY' or 'MM/DD/YYYY'.
The date formatting is handled by react-intl. This works fine when converting from a date to a string (via formatDate). However, I need to retrieve the pattern as described above.
My goal is to do something like
dateFormat = this.props.intl.extractDateFormat() // returns 'DD.MM.YYYY'
I have found this similar question, but the only answer relies on parsing the string, which I cannot do, because I do not know whether Day or Month will come first in the formatted date.
If it is possible to convert this string to a date and somehow retrieve the format from momentjs, that would also be a good solution.
I was able to get the date format from react-intl. To do this, I defined an example date and had it formatted by react-intl, and then parsed the format by referring to the original string.
My component which is exported as injectIntl(Component) has this method:
deriveDateFormat = () => {
const isoString = '2018-09-25' // example date!
const intlString = this.formatDate(isoString) // generate a formatted date
const dateParts = isoString.split('-') // prepare to replace with pattern parts
return intlString
.replace(dateParts[2], 'DD')
.replace(dateParts[1], 'MM')
.replace(dateParts[0], 'YYYY')
}
The date will e.g. be formatted to '09/25/2018', and this function would return 'MM/DD/YYYY', a format which can be used by Moment.js.
This function only works if you know that the month and day will always be displayed with two digits. It would fail if the format is something like 9/25/2018.
I have not found a way to extract the date format from react-intl directly.

Convert a jmeter variable of milliseconds to a formatted date

I cant seem to convert a date in milliseconds (1488520800000) extracted from JSON and put into a variable into a formatted date (2017-03-02). Here's my code:
import java.text.*;
import java.util.*;
SimpleDateFormat source = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat target = new SimpleDateFormat("yyyy-MM-dd");
Date date = source.parse(vars.get("varReviewDatevalue"));
String newDate = target.format(date);
vars.put("varFormattedReviewdateValue",newDate);
Here's the error I get:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.text.*; import java.util.*; log.info("value for variable: 14885208 . . . '' : Typed variable declaration : Method Invocation source.parse
What's weird is that I got similar code to work fine for an extracted date like: March 2, 2017. I can't figure out why the date represented in mills is not converting to a date. Any ideas?
I was using the wrong jmeter element. This post helped me alot: JMeter: Converting extracted time stamp value to date format
I put this code into a JSR223 Sampler and everything worked
import java.text.*;
long timeStamp = Long.parseLong(vars.get("varReviewDatevalue"));
Date date = new Date(timeStamp);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
TimeZone tzInAmerica = TimeZone.getTimeZone("America/Denver");
formatter.setTimeZone(tzInAmerica);
String dateFormatted = formatter.format(date);
vars.put("varFormattedReviewdateValue", dateFormatted);
log.info(dateFormatted);
log.info(vars.get("varFormattedReviewdateValue"));

How to create a datetime in apex given a datetime string?

With apex, I pass a string like:
2017-02-05T01:44:00.000Z
to an apex function from javascript, however, when attempting to turn it into a datetime, it gives me invalid date/time error. I can create a date with it like
date newdate = date.valueOf(dateString);
but if I do datetime newdate = datetime.valueOf(dateString) I get the error. I don't get why it sees the string as incorrectly formatted to give invalid date/time. When I create just a date instead of datetime, I lose the time and it sets it to 00:00:00.
Thank you to anyone with some insight on how to create the datetime in apex! I have been trying to find the apex format and from what I see. I can't understand why it thinks this is invalid.
Try this.
String inpputString = '2017-02-05T01:44:00.000Z';
DateTime resultDateTime = DateTime.ValueofGmt(inpputString.replace('T', ' '));
System.Debug('resultDateTime>> '+resultDateTime);
Output:
10:10:41:011 USER_DEBUG [4]|DEBUG|resultDateTime>> 2017-02-05 01:44:00

SAPUI5 - Dateformat - How format a date with Dateformat

let's say I have a Date as a String, formated in yyyy-MM-dd, and I want it to be formated as style:"short".
I want just to use Dateformat.
I used this https://openui5.hana.ondemand.com/#docs/guide/91f2eba36f4d1014b6dd926db0e91070.html to get an idea of how to use DateFormat.
But I can't see, what's wrong with my code:
date: function(sdate) {
var regex = "[0-9]{4}-[0-9]{2}-[0-9]{2}";
if (!sdate.match(regex))
return "no valid date given";
jQuery.sap.require("sap.ui.core.format.DateFormat");
var oDateFormat = sap.ui.core.format.DateFormat.getInstance({pattern: "yyyy-MM-dd", style: "short"});
return oDateFormat.format(sdate); //date should be returned here in "short"-style
}
The console tell's me
TypeError: j.getTime is not a function.
Also it seems like the WebIDE doesn't know a function Datetime.format().
Can you help?
You'd probably reread the documentation in your link: to convert String into JS Date, you have to use DateFormat.parse method.

How to parse string with date, but without time in local format to ZonedDateTime?

This question is similar to How to parse ZonedDateTime with default zone? but addinitional condition.
I have a string param that represent a date in UK format: "3/6/09". It doesn't contain time, only date. But may contain it and even time zone.
And I want to parse it to ZonedDateTime.
public static ZonedDateTime parse(String value) {
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(SHORT).withLocale(Locale.UK).withZone(ZoneId.systemDefault());
TemporalAccessor temporalAccessor = formatter.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
if (temporalAccessor instanceof ZonedDateTime) {
return ((ZonedDateTime) temporalAccessor);
}
if (temporalAccessor instanceof LocalDateTime) {
return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
}
return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
}
But, it fails with exception:
java.time.format.DateTimeParseException: Text '3/6/2009' could not be parsed at index 6
It's a bug for me, or isn't?
In my opinion is not a bug. Your approach is flawed.
First of all you are returning a ZonedDateTime so it is expected that the String contains full date, time and zone information. The string "3/6/09" should be parsed to a LocalDate.
Second, you are delegating a runtime detection of format to the library. Again, you should be parsing/formatting an expected format. Your application should know wether is expecting a full date & time or a partial (only date or only time).
Anyway you will have more luck detecting the format and then using different parsing methods.
Only local date:
DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.parse(value, LocalDate::from)`
Zoned date and time:
DateTimeFormatter
.ofLocalizedDateTime(FormatStyle.SHORT, FormatStyle.SHORT)
.parse(value, ZonedDateTime::from)`
The format used can be seen using the getLocalizedDateTimePattern() method:
String fmt = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.SHORT, FormatStyle.SHORT, IsoChronology.INSTANCE, Locale.UK);
The result is "dd/MM/yy HH:mm".
As such, the format is expecting both a date and a time with a space separator, so that is what must be provided.
In addition, the format/parse expects there to be two digits for the day-of-month and two digits for the month-of-year. Thus, you would need to pass in "03/06/09 00:00" in order to get the result you expect, in which case you can parse directly to a LocalDateTime.
Alternatively, use ofLocalizedDate():
DateTimeFormatter formatter =
DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT).withLocale(Locale.UK);
LocalDate date = LocalDate.parse("03/06/99", formatter);
Note that the input must still have two digits for the day and month.
Alternatively, parse using a specific pattern that can handle the missing leading zeroes:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("d/M/yy");
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"
Update: Lenient parsing also handles this case:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseLenient().appendPattern("dd/MM/yy").toFormatter();
LocalDate date = LocalDate.parse("3/6/99", formatter);
LocalDate date = LocalDate.parse("03/06/99", formatter);
// handles both "3/6/99" and "03/06/99"