D: print number of current month instead of its name - datetime

I need to get number of current month instead of getting its name:
void main()
{
SysTime dt = Clock.currTime();
writeln(dt.month);
}
The output is:
oct
but I need 10. How I can get it? I found only one solution cast it to int, but is there any better way, or it's ok?

Use std.conv.to() for converting types.
This seems to work:
import std.conv;
import std.datetime;
import std.stdio;
void main()
{
SysTime dt = Clock.currTime();
writeln(dt.month.to!ushort);
}
10

If you just need it for printing then use writefln like below.
writefln("%d", dt.month);
If you need to use the number then the to template can be used, which in general should be used for conversions.
writeln(dt.month.to!size_t);
// or ...
writeln(to!size_t(dt.month));
Ultimately you can also cast it.
writeln(cast(size_t)dt.month);

There is no need for explicit conversion as the Month enum's type is int by default (check more about enums).
import std.datetime;
// Month is an enum - http://dlang.org/phobos/std_datetime.html#.Month
Month month = Clock.currTime().month;
int monthnum = 0 + month; // works

Related

How to ignore milliseconds and format using DateTimeFormatter

I am trying to use DateTimeParser and DateTimeFormatter to format the date time. My requirement is to format the input string to "yyyy-MM-dd'T'HH:mm:ssZ" format irrespective of whether the input has milliseconds or not. I am using below code to parse the input. But so far I can get it working for only with or without milliseconds.
This is my method:
public static DateTime convertDateTime(String dateTime){
DateTimeParser parsers = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").getParser();
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(parsers ).toFormatter().withLocale(Locale.US).withChronology(ISOChronology.getInstanceUTC());
return DateTime.parse(dateTime,formatter);
}
Imports used :
import org.joda.time.DateTime;
import org.joda.time.chrono.ISOChronology;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
I want my code to accept 2 different input forms(with or without milliseconds) and returns one DateTime without milliseconds.
Examples:
input can be:
2020-10-01T12:05:22.458-04:00
2020-10-01T12:05:22-04:00
Output:
2020-10-01T12:05:22-04:00
Any help on this will be greatly appreciated. Thanks!
You are reinventing the ISO_ZONED_DATE_TIME.
For this format, milliseconds are already optional. You only have to truncate them when present, to get your desired result. The format is even the standard, so the code is as simple as:
String[] samples = {
"2020-10-01T12:05:22.458-04:00",
"2020-10-01T12:05:22-04:00",
};
for(String s: samples) {
ZonedDateTime parsed = ZonedDateTime.parse(s).with(ChronoField.MILLI_OF_SECOND, 0);
System.out.println(parsed);
}
2020-10-01T12:05:22-04:00
2020-10-01T12:05:22-04:00
Note that I used MILLI_OF_SECOND to make the solution more intuitive regarding your task of removing the milliseconds. Actually, milliseconds are just nanoseconds with a lower precision, so you could use the even simpler ZonedDateTime.parse(s).withNano(0), once it has been understood.
Or, as suggested by Ole V.V., ZonedDateTime.parse(s).truncatedTo(ChronoUnit.SECONDS), which might be even easier to grasp.

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

Is there a better way to encode a (MS) DateTime as an Int?

BACKGROUND (ok to ignore/skip):
I feel like there should be a better way to do what I'm doing, but I don't know what it is and I think my solution works, but I thought I'd ask in case there is something more elegant or faster or whatever.
I am developing a web page with MS Razor MVC which uses Html.DropDownList, which gives a pick list UI control which maps choices as display strings to integer ID codes. (I don't think I can have it map strings to DateTime values.)
But in a couple of cases, I want to choose from dates that are stored as DateTime objects. I realize I could make yet another table in memory that relates ID codes to DateTime values, but I thought instead (and also because I think I may want to encode dates as ints for yet another workaround of web page annoyances), I would encode the date as an int.
PROBLEM:
How best to convert the date of a DateTime object as an int value, and then later set a DateTime's date back to that date from the encoded int. The main ugliness of my solution is that DateTime provides a read-only DayOfYear function, but no way I know of to set a date back to (Date, DayOfYear), so I wrote a method with a loop, which is cute but probably slowish.
MY CURRENT (OK) SOLUTION:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}
Ho about to format the timestamp as POSIX time (POSIX time / Unix time, see http://en.wikipedia.org/wiki/Unix_time)?
I had a similar problem myself and found a great solution here: Convert a Unix timestamp to a .NET DateTime
From the link:
DateTime ConvertFromUnixTimestamp(double timestamp)
{
}
double ConvertToUnixTimestamp(DateTime date)
{
}

How can I convert java.util.Date to org.joda.time.DateTime?

I have to use java.util.Date class as field type in a table.
But I would like to change the display format of the date field with help of joda time (confortable, prefered to use), thats why I want to convert a Date to DateTime.
I know I oversee something, because there is no such a question in stackoverflow :) but I could not find the soulution among the DateTime constructors and so on.
The reverse conversion DateTime.toDate();
exists, but what about the opposite way ?
Thanks for the answers in advance.
Cs
In Vaadin, if you want to change display format in a table without joda, you simply override the method protected String formatPropertyValue(Object rowId, Object colId,
Property property)
Here an example to do it :
Table t = new Table() {
#Override
protected String formatPropertyValue(Object rowId, Object colId,
Property property) {
Object v = property.getValue();
if (v instanceof Date) {
Date dateValue = (Date) v;
return new SimpleDateFormat("yyyy-MMMM-dd").format(dateValue);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
Regards
Éric
Yes, Use Joda-Time
Definitely use Joda-Time or the java.time package in Java 8 (inspired by Joda-Time). The old java.util.Date and java.util.Calendar classes are notoriously troublesome, confusing, and outmoded.
Also, read the Wikipedia pages on UTC and ISO 8601.
Yes, Pass Date To Joda-Time Constructor
➔ Yes indeed, you can pass a java.util.Date object to the constructor of a Joda-Time DateTime object.
The API doc is a bit confusing as this apparently falls into the catch-all version of the constructor taking an java.lang.Object instance. If that Object is in fact a java.util.Date, Joda-Time will extract its millisecond-count-since-epoch and use that number as its own.
Time Zone
A DateTime constructor also assigns a time zone. By default, the JVM’s current default time zone is assigned. I recommend you always pass a desired time zone rather than rely implicitly on the default even if that means calling getDefault.
Example Code
Here is some example code in Joda-Time 2.5 showing how to pass a java.util.Date to a Joda-Time constructor.
java.util.Date date = new java.util.Date();
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTimeMontreal = new DateTime( date , zone );
DateTime dateTimeUtc = dateTimeMontreal.withZone( DateTimeZone.UTC ); // Adjust to another time zone.
Dump to console.
System.out.println( "date: " + date ); // Misleading output. A j.u.Date is in UTC but its toString method applies JVM’s current default time zone.
System.out.println( "dateTimeMontreal: " + dateTimeMontreal );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
When run.
date: Sat Oct 18 18:54:55 PDT 2014
dateTimeMontreal: 2014-10-18T21:54:55.740-04:00
dateTimeUtc: 2014-10-19T01:54:55.740Z
As shown in the Question, to go from a DateTime to java.util.Date, call toDate.
java.util.Date date = dateTimeMontreal.toDate();

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