Using str2date with strings that also contain a time - axapta

I have a method which, given an .NET XmlNode containing an ISO 8601 date in the inner text, will convert it to an X++ date object.
if (CLRInterop::isInitialized(childNode))
{
return str2Date(childNode.innerText(), 321);
}
else return maxDate();
This works great if supplied a string which contains only a date (eg: 2019-03-21), but as soon as a time is also provided in this string (eg: 2019-03-21T00:00:00), it will return nothing.
The easiest fix for this would be just to strip everything past the first 10 characters, but this would break again if for some reason the string only contains 2 characters for the year. Is there a more robust way of handling strings including times in a call to str2date?

I just wrote this job with a bunch of examples. The very first line might be what you want. You can just create this as a new job in AX and then put a breakpoint on the first line and step through each to see what happens, or modify to experiment.
It looks like your string is standard ISO format, which I cover below various ways too.
static void DateTimeJob(Args _args)
{
// This line looks about what you want
utcDateTime utcDateTimeFromString = DateTimeUtil::anyToDateTime("2019-03-21T00:00:00");
// ISO standard format. You can just assign it directly without quotes
utcDateTime utcDateTimeISOFormat = 2019-03-21T00:00:00;
// Misc vars for below
utcDateTime utcNow;
System.DateTime systemDateTime;
date dateOnly;
str systemDateTimeStr;
// Look at
// DateTimeUtil::<> // This has all sorts of useful functions
// str2datetime() // May be useful to you
try
{
// How to go from AX UTC to System.DateTime
systemDateTime = Global::utcDateTime2SystemDateTime(DateTimeUtil::utcNow());
// How to go from System.DateTime to AX UTC
utcNow = Global::clrSystemDateTime2UtcDateTime(System.DateTime::get_UtcNow());
// How to get ONLY the date portion from a UTC
dateOnly = DateTimeUtil::date(utcNow);
// Cast to string for output
systemDateTimeStr = systemDateTime.ToString();
// Output a few examples
info(strFmt("%1, %2, %3",
systemDateTimeStr,
utcNow,
dateOnly));
}
catch (Exception::CLRError)
{
error(AifUtil::getClrErrorMessage());
}
}

Related

Changing the Session Languge leads to "java.text.ParseException: Unparseable date

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.

Java 8 Parse ISO-8601 date ignoring presence (or absence) of timezone

My application should be able to parse date ignoring timezone (I always know for sure that it is UTC). The problem is that the date might come in both following forms -
2017-09-11T12:44:07.793Z
0001-01-01T00:00:00
I can parse the first one using LocalDateTime, and the second one using Instant class. Is there a way to do that using a single mechanism?
P.S. I'm trying to avoid hardcoding Z at the end of the input string
If the Z offset is optional, you can use a java.time.format.DateTimeFormatterBuilder with an optional section:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// optional offset
.optionalStart().appendOffsetId()
// create formatter
.toFormatter();
Then you can use the parseBest method, with a list of TemporalQuery's that tries to create the correspondent object. Then you check the return type and act accordingly:
Instant instant = null;
// tries to create Instant, and if it fails, try a LocalDateTime
TemporalAccessor parsed = fmt.parseBest("2017-09-11T12:44:07.793Z", Instant::from, LocalDateTime::from);
if (parsed instanceof Instant) {
instant = (Instant) parsed;
} else if (parsed instanceof LocalDateTime) {
// convert LocalDateTime to UTC instant
instant = ((LocalDateTime) parsed).atOffset(ZoneOffset.UTC).toInstant();
}
System.out.println(instant); // 2017-09-11T12:44:07.793Z
Running with the second input (0001-01-01T00:00:00) produces the Instant equivalent to 0001-01-01T00:00:00Z.
In the example above, I used just Instant::from and LocalDateTime::from, so the formatter tries to first create an Instant. If it's not possible, then it tries to create a LocalDateTime. You can add as many types you want to that list (for example, I could add ZonedDateTime::from, and if a ZonedDateTime is created, I could just convert to Instant using toInstant() method).
As you know for sure that the input is always in UTC, you can also set it directly in the formatter:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// optional offset
.optionalStart().appendOffsetId()
// create formatter with UTC
.toFormatter().withZone(ZoneOffset.UTC);
So you can parse it directly to Instant:
System.out.println(Instant.from(fmt.parse("2017-09-11T12:44:07.793Z"))); // 2017-09-11T12:44:07.793Z
System.out.println(Instant.from(fmt.parse("0001-01-01T00:00:00"))); // 0001-01-01T00:00:00Z
You can "parseBest", like this:
DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss[Z]");
Temporal parsed = parser.parseBest(inputString, Instant::from, LocalDateTime::from);
Then you should check what did get parsed, and act accordingly.
The parseBest method will work with any type of TemporalQuery, including most of from methods available on java.time classes. So you can lengthen that list with LocalDate.from, for example.
You can also use that method and lambdas to coerse parse results to the type you want without having instanceof checks that are external for result resolution (although not without one cast):
Instant parsed = (Instant) parser.parseBest(inputString,
Instant::from,
interResult -> LocalDateTime.from(interResult).atZone(ZoneOffset.UTC).toInstant())
Notice that second option uses lambda that converts LocalDateTime to ZonedDateTime and then to Instant, so the parse results are always coersed to Instant.

ZonedDateTime: I would like parse() to fail on invalid date

I guess I just expected this to give me a parsing exception, but it didn't. I would like the parse to fail if the date is invalid. (That's what I need to know)
Added note: Using Feb. 30th as an invalid date: (In fact, what I need to do is receive five strings; year, month, day, hour, minute, which I assembly into str (below) and see if they come together as a valid date-time (in ZONE_ID).
String ZONE_NAME = "America/Los_Angeles";
ZoneId ZONE_ID = ZoneId.of(ZONE_NAME);
String ldtfPattern = "yyyy/MM/dd HH:mm";
DateTimeFormatter localDateTimeFormatter =
DateTimeFormatter.ofPattern(ldtfPattern);
String str = "2016/02/30 21:09";
try {
zdt = ZonedDateTime.parse(str, localDateTimeFormatter().withZone(ZONE_ID));
} catch(DateTimeParseException e) {
return null;
}
return zdt;
The string value of zdt after the parse above is
2016-02-29T21:09-08:00[America/Los_Angeles]
A little birdie told me to try using withResolverStyle() set to STRICT. With that, the only other trick I needed to make this work was to incorporate the era into my year. So the changes to the above are:
String ldtfPattern = "uuuu/MM/dd HH:mm";
and
zdt = ZonedDateTime.parse(str,
getLocalDateTimeFormatter().withZone(ZONE_ID).withResolverStyle(ResolverStyle.STRICT));
And this is working for me.

Adding comma separators to numbers, asp.net

I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function

Javascript Date Localization

I'm working with an ASP.NET app with localization and globalization. I'm having some difficulty understanding how to get the Date() function in javascript to work properly given the user's environment. My user base is split between Mexico (spanish) and the US (english). Since the Mexico date format is dd/mm/yyyy and the english format is mm/dd/yyyy, the standard Date(strDate) javascript constructor does not work for me.
Does anyone know the best way to handle globalization/localization of a javascript Date value? I have some business rules to enforce like dateA must be 90 days prior to dateB and dateB cannot exceed today.
Take a look at datejs, it handles localization very nicely. It comes with a lot of globalization setups. You just load the globalization setup of your current CultureInfo and datejs takes care of the rest.
Matt Kruse developed a really interesting date library which should help with your particular case.
Here's a snippet of the method you should use for the issue you mentioned:
// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d MMM d, y MMM d,y y-MMM-d d-MMM-y MMM d
// M/d/y M-d-y M.d.y MMM-d M/d M-d
// d/M/y d-M-y d.M.y d-MMM d/M d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
var preferEuro=(arguments.length==2)?arguments[1]:false;
generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
var d=null;
for (var i=0; i<checkList.length; i++) {
var l=window[checkList[i]];
for (var j=0; j<l.length; j++) {
d=getDateFromFormat(val,l[j]);
if (d!=0) { return new Date(d); }
}
}
return null;
}
You could use: var a = Date.parseLocale(value, formats);
If you provide no custom formats, this function uses the Sys.CultureInfo.CurrentCulture property to determine the culture value.
You can take a look on: http://msdn.microsoft.com/en-us/library/bb397521.aspx
I wrote an answer to this here. It uses the toLocalString to determine MM/DD/YYY, DD/MM/YYYY,...
https://stackoverflow.com/a/18154195/119741

Resources