Getting current date and time in specific format x++ 2012 - datetime

I need to get the date/time in this format.
2016/05/25 17:08:22
X++ 2012, . i attempted to use DateTimeUtil::getSystemDateTime()) but not sure the correct parameters

The following job should give you the idea how to do the formatting.
static void FormatDateTimeJob(Args _args)
{
utcDateTime now = DateTimeUtil::utcNow();
str formattedOutput;
formattedOutput = DateTimeUtil::toFormattedStr(
now,
321,
DateDay::Digits2,
DateSeparator::Slash,
DateMonth::Digits2,
DateSeparator::Slash,
DateYear::Digits4,
TimeSeparator::Colon,
TimeSeparator::Colon);
info(formattedOutput);
}
Of course you may want to apply a timezone prior to formatting the value like so
now = DateTimeUtil::applyTimeZoneOffset(
now,
DateTimeUtil::getClientMachineTimeZone());

Related

How to format a date in Visual Basic?

In Visual Basic, I have an object with an ItemDate key in it with the value being assigned to a label in ASPX. Here is the code:
lblItemDate.Text = .ItemDate
The result on the front end is '2021/11/15'. I want the result to be: 'November 15, 2021'
What do I need to do in Visual Basic to make the result on the front end be 'November 15, 2021' instead of '2021/11/15'?
In another VB file, the ItemDate object key is created this way:
oItem.ItemDate = Trim(odbcReader("ItemDate").ToString)
Assuming you really have a .Net DateTime struct:
lblItemDate.Text = .ItemDate.ToString("MMMM dd, yyyy")
Otherwise you have a string, in which case you want to parse into a .Net DateTime struct so you can use the same ToString() call above:
Dim MyDate As DateTime = DateTime.ParseExact( .ItemDate, "yyyy/MM/dd")
lblItemDate.Text = MyDate.ToString("MMMM dd, yyyy")
Even better if you can update your code so ItemDate is a DateTime value in the first place, and the Parse() call is moved to the point where the object is first created.
It's been a while, so I don't recall whether the .ItemDate shortcut is available in the context of a function call. You may need to use the full version of the variable name.
Besides the .Net functions mentioned in another answer, which work across different languages, there is also the Format(..) function traditionally included with professional implementations of BASIC since the early 70's (I first used it in DEC's BASIC-Plus in 1976).
To get 'November 15, 2021' you'd do it like this:
lblItemDate.Text = Format(.ItemDate, "MMMM d, yyyy")

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.

Get time format according to spreadsheet locale?

I want to store a Javascript Date() object in a spreadsheet with correct format according to spreadsheet's locale (SpreadsheetApp.getActive().getSpreadsheetLocale()).
Is there a way to get the country specific (date and) time format string from the spreadsheet locale?
E.g. when locale is de_DE, time format string as hh:mm
but when locale is da_DK, time format string as hh.mm
Interesting as well how to get the countries currency format.
BTW when I have date and time in de_DE and than change to da_DK, dates are reformatted (23.01.2020 -> 23/01/2020) but times are not (it stays as 22:59). Is that an error in Spreadsheet?
Dates in JavaScript have the method toLocaleDateString, which return a string formatted according to the specified locale. But this doesn't seem to work in Apps Script.
If you're open to using an Apps Script Web App for this, you could use this toLocaleDateString in your client-side script (that is, in a script tag in your HTML).
If that's not the case, I think your best option would be to create the relationship between formats and locales yourself, because Apps Script doesn't have a built-in method to achieve that. You could, for example, use a switch statement that would check the locale, and then format the date accordingly with Utilities.formatDate, the tool Apps Script uses to format dates. It could be something along the following lines:
var locale = SpreadsheetApp.getActive().getSpreadsheetLocale();
var formattedDate;
switch (locale) {
case 'de_DE':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh:mm");
break;
case 'da_DK':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh.mm");
break;
// ...
}
return formattedDate;
Reference:
toLocateDateString
Apps Script Web Apps
Utilities.formatDate
I hope this is of any help.
Sorry for that, however I found a function that would be worth checking out, it's toLocaleDateString() and toLocaleTimeString (), they deliver the local date and time format.
Please check
Formato fechas JavaScript.
I did the test from Google Apps Script and it throws me the following
function pruebafecha() {
var d = new Date();
var n = d.toLocaleDateString();
var h = d.toLocaleTimeString();
Logger.log(n);
Logger.log(h);
}
This is the answer(Colombia):
[20-01-24 16:47:50:286 EST] 24 de enero de 2020
[20-01-24 16:47:50:287 EST] 16:47:50 EST
A JavaScript Date object includes date, time and timezone. When Google Apps Script pass a Date object to the spreadsheet using setValue() / setValues() the value is displayed according to the cell number formatting using the spreadsheet timezone.
If the cell formatting is set to Automatic by default the date will be displayed accordingly to the spreadsheet locale.
If you want to force the cell to display a date in an specific format use Class Range setNumberFormat / setNumberFormats
If you don't want to use the above methods and don't want to rely on the spreadsheet locale and automatic cell format then instead of passing a Date object pass the value as an string prepending it with an ' (apostrophe, single quote character) to prevent that that automatic data type parsing changes the value and it's format.
Related
Javascript in Google Sheets script: help using setNumberFormat
I don't know very well the configuration of the sheet you mention. However, I share a code that I use to print the date and time of data submission of a form.
var d = new Date();
var hour = d.getHours()-1;
var min = d.getMinutes();
var day = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if (month<10) {dia = day+"/"+"0"+month+"/"+year;}
else {dia = day+"/"+month+"/"+year;}
if (min<10){time = hour+":"+"0"+min;}
else {time = hour+":"+min;}
What I do in the code is to take the values โ€‹โ€‹of day, month and year, I add 1 to the value of month because it takes values โ€‹โ€‹[0:11] => [Jan, Dec].
Then I build the format I want from date and time, you can notice that I have 1 left to the hours, because when I did the tests I noticed that the time of the script was one hour above.
I use google translate, I hope it is understood.

Using str2date with strings that also contain a time

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());
}
}

EntityFunction.TruncateTime not working in my query

I am using Linq to entityframework to query some infomration. I am trying to use entityfunction.truncatetime and it doesnt seem to work as expected. here is my sample query
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = EntityFunctions.TruncateTime(d.RequestedMoveDate)
The requesteddate doesnt seem to truncate the time part and I am still getting the both Date and time.
Am I missing something here?
In .NET, the DateTime class actually represents both a date and a time. Internally, this is stored as a numeric value represented by the number of 100-nanosecond "ticks" since Midnight, January 1, 1001 AD. This number gets "converted" when it's displayed (either in output or in a debugger). This conversion is done via a format string.
Even if you truncate a DateTime's time portion, it still has a time... it's just 00:00:00, and if you don't want to see that time, you need to adjust your format string to not convert that.
Thus, if you do something like this: DateTime.Now.Date it will display `10/15/2012 00:00:00" if you use the default date conversion string (or whatever is the default format for your culture).
If you want to only display the Date portion, then you must do something like myDate.ToShortDateString() or myDate.ToString("d").
EntityFunctions is a set of tools designed to be used in Linq to Entities queries, because doing DateTime formatting is not normally allowed in a query.
For example, this code does not work:
var q = from x in dc where x.BirthDate == DateTime.Now.AddYears(-15).Date select x;
You have to do it like this:
var q = from x in dc
where x.Birthdate == EntityFunctions.TruncateTime(DateTime.Now.AddYears(-15))
select x;
This will then generate the correct SQL to do date comparisons in SQL code. This is what the EntityFunctions are designed for, not truncating dates in the select portion (although it does work). But, even though the date is truncated, it will still have a Time component, it will just be 00:00:00, and you must use a date format string to present it to your users in the manner you intend.
cant you use ToShortDateString() like below?
List<DateTime> time = new List<DateTime>();
time.Add(DateTime.Now);
var WhatDate = from date in time
select new { Date = date.ToShortDateString() };
In your case try this
From d In Request
Where d.Requestor= "XXXX" And d.ProcessedFlag = "N"
Select new{ RequestID = d.RequestID, RequestReason = d.RequestReason.ItemValue, RequestType = d.RequestType.ItemValue, RequestedDate = d.RequestedMoveDate.ToShortDateString()};

Resources