How to set the Eclipse date variable format? - eclipse

How can I set the format for the ${date} variable which can be used in Eclipse templates?

Update February 2016: bug 75981 is officially fixed!
See Jmini's answer below
Update July 2015, 6 years later:
The bug mentioned below seems fixed in Eclipse 4.x.
Eric Wang comments below:
#date ${id:date('YYYY-MMM-dd')} ${time}
this give me English datetime format in eclipse 4.
Original Answer 2009 Eclipse 3.x
Argh! There is a long standing bug just for that: bug 75981
The ${date} variable could be enhanced to accept an argument (similar to other
parameterizations added in 3.3M1), e.g. ${d:date(format)}, where format is a pattern for SimpleDateFormat.
The only alternative would be to modify the class SimpleTemplateVariableResolver (as described in this thread), from the package org.eclipse.jface.text.templates. (You have here an example of such an extension).
This thread mentions the sources where you can find the class.
\eclipse\plugins\org.eclipse.platform.source_3.1.0\src\org.eclipse.text_3.1.0\src.zip
Example:
public static class Date extends SimpleTemplateVariableResolver {
/**
* Creates a new date variable
*/
public Date() {
super("date", TextTemplateMessages.getString("GlobalVariables.variable.description.date")); //$NON-NLS-1$ //$NON-NLS-2$ }
protected String resolve(TemplateContext context) {
//return DateFormat.getDateInstance().format(new java.util.Date());
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
return df.format(new java.util.Date()); } }

You could tell Eclipse to use a specific locale different from that of your operating system. Eclipse 3.5 (64 bit) doesn't use the MacOS X region setting. MacOS X english installation language with Germany as country provides a wrong date format.
You can fix it for your Eclipse installation when you append following lines to your eclipse.ini:
-Duser.language=de
-Duser.region=DE

I have fixed Bug 75981 with Eclipse Neon M5. You can download this Milestone Release here:
http://www.eclipse.org/downloads/index-developer.php
… or wait until June 2016 for the official Neon Release.
Here a quick description of how it works:
As before you can use the date variable with no argument. Example: ${date}
You can use the variable with additional arguments. In this case you will need to name the variable (since you are not reusing the date somewhere else, the name of the variable doesn't matter). Example: ${mydate:date}
The first parameter is the date format. Example: ${d:date('yyyy-MM-dd')}
The second parameter is the locale. Example: ${maDate:date('EEEE dd MMMM yyyy HH:mm:ss Z', 'fr')}
More info about this feature on my blog: Bug 75981 is fixed!

Additional information for those stumbling over this lately (like me):
For ISO 8601 date format, one can use the language settings fr-CA.

Related

GWT compiling java to javascript and time format

in Java I set the date as time in mSec since 1970, e.g. futuredate=1640995200000l //1 Jan 2022.
When this is compiled into JavaScript by GWT, I believe it uses the Jsdate library which says it is a native javascript date object
1 jan 2022 ends up as this object in the JavaScript _.futuredate={l:3120128, m:391243, h:0}
Can someone help me interpret this format please, it doesn't quite make sense to me
thanks
To work with date and time on the GWT client side one can use com.google.gwt.i18n.shared.DateTimeFormat. com.google.gwt.i18n.shared.DateTimeFormat.PredefinedFormat includes already many predefined formats, but you can naturally use your own, such as "EEEE, y MMMM dd".
Based on your example:
Date myDate = DateTimeFormat.getFormat("dd.MM.yyyy").parse("01.01.2022");
DateTimeFormat myFormat = DateTimeFormat.getFormat(PredefinedFormat.ISO_8601);
String s = myFormat.format(myDate);
The first line only simulates the date that you already set in Java and it is meant to show another example of a date format and how to parse a String.

How to get the Date with offset taken into account from XmlGregorianCalendar?

i have an XMLGregorianCalendar in this form: 2019-06-24T18:18:55.007+02:00
How can i get the right date (with offset taken into account) in String like this : 24/06/2019 16:18 ?
You tagged your question java-6. Yet I am presenting the modern answer using java.time, the modern Java date and time API. This is available in Java 6 through ThreeTen Backport (see the link at the bottom).
Depending on from where you got your XMLGregorianCalendar you may not need to have one. If I understood correctly, this class was used for representing dates and times in XML documents, where they are formatted like for example 2019-06-24T18:18:55.007+02:00. This format is close enough to ISO 8601 that the classes of java.time can parse it directly, which we prefer:
Locale userLocale = Locale.forLanguageTag("mt-MT"); // Maltese Malta
DateTimeFormatter displayFormatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT)
.withLocale(userLocale);
String fromXml = "2019-06-24T18:18:55.007+02:00";
OffsetDateTime dateTime = OffsetDateTime.parse(fromXml);
String formattedUtcDateTime = dateTime.withOffsetSameInstant(ZoneOffset.UTC)
.format(displayFormatter);
System.out.println(formattedUtcDateTime);
Output from this snippet is (tested in Java 1.7.0_67 with ThreeTen Backport version 1.3.6):
24/06/2019 16:18
Assuming that the formatting is for displaying to a user, I recommend using Java’s localized formats. I have chosen Maltese locale because it matches your requested format exactly. If your user is in a different locale, you should still consider the format of that locale.
Converting from XMLGregorianCalendar
If you got your XMLGregorianCalendar from a legacy API that you cannot afford to change just now, there are a number of options for converting it.
One is to get the string back from the XMLGregorianCalendar:
XMLGregorianCalendar xmlgc = DatatypeFactory.newInstance()
.newXMLGregorianCalendar("2019-06-24T18:18:55.007+02:00");
String fromXml = xmlgc.toString();
Now the rest is as above. Pro: it’s short, and I don’t think there are any surprises in it. Con: To me formatting back into the original string and parsing it once more feels like the detour.
Another option goes through the outdated GregorianCalendar class:
GregorianCalendar gc = xmlgc.toGregorianCalendar();
ZonedDateTime zdt = DateTimeUtils.toZonedDateTime(gc);
String formattedUtcDateTime = zdt.toOffsetDateTime()
.withOffsetSameInstant(ZoneOffset.UTC)
.format(displayFormatter);
Pro: I think it’s the official conversion. Con: it’s a line longer, and as I said, it uses the poorly designed and long outdated GregorianCalendar class.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
The working solution i have found:
private String getFormattedDate(final XMLGregorianCalendar xmlGregorianCalendar) {
Date time = xmlGregorianCalendar.toGregorianCalendar().getTime();
Date rightDate = DateUtils.addMinutes(time, - xmlGregorianCalendar.getTimezone());
String formatedDate = DateHelper.format(DateHelper.YYYYMMDDHHMMSS_DASH_COLONS, rightDate);
return formatedDate;}

How to convert local date to UTC in Mirth?

In Mirth I receive a local datetime string (201801011000) which I need to convert to UTC. I soon found out using the classic js new Date() doesn't work well.
This for example:
var d = new Date("2018-01-01 10:00");
logger.info(d.toString());
gives me an Invalid Date.
So after some more searching I found I can do this:
var d = DateUtil.getDate("yyyyMMddHHmm", "201801011000");
and from here I'm stuck. I don't know how I can convert this to UTC. Local server timezone is assumed which is enough for now, but in the future I also need to set a specific non-local timezone.
I tried to get the methods I can use with Object.getOwnPropertyNames(d), but that gives me the helpfull TypeError: Expected argument of type object, but instead had type object
I also tried looking up the java docs for DateUtil and tried some methods from that, but nothing worked.
Does anybody know how I can convert datestring from local time to UTC? All tips are welcome!
Ok, after messing around with this for about two full days I finally found a solution. In the end I had to tap into Java, but since I couldn't import any java dependencies I had to use their direct class path (e.g.: java.text.SimpleDateFormat).
In the end this is what worked for me:
var datestr = "201207011000".slice(0, 12); // This is just a datetime string to test with
var formatter_hl7 = new java.text.SimpleDateFormat("yyyyMMddHHmm");
formatter_hl7.setTimeZone(java.util.TimeZone.getTimeZone("CET"));
var formatter_utc = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm");
formatter_utc.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
var date_in_utc = formatter_utc.format(formatter_hl7.parse(date_str));
Regardless, I wish you all a beautiful day!
tl;dr
Do not use DateUtil whatever that is. (Perhaps Apache DateUtils library?)
Do not use terrible old date-time classes such as java.util.Date.
Use the modern industry-leading java.time classes.
Code for parsing a string lacking an offset, then assigning an offset of zero for UTC itself.
LocalDateTime // Represents a date and a time-of-day but without any concept of time zone or offset-from-UTC. NOT a moment, NOT a point on the timeline.
.parse(
"201801011000" ,
DateTimeFormatter.ofPattern( "uuuuMMddHHmm" )
)
.atOffset( ZoneOffset.UTC ) // Assign an offset-from-UTC. Do this only if you are CERTAIN this offset was originally intended for this input but was unfortunately omitted from the text. Returns an `OffsetDateTime`.
.toInstant() // Extract an `Instant` from the `OffsetDateTime`. Basically the same thing. But `Instant` is always in UTC by definition, so this type is more appropriate if your intention is to work only in UTC. On the other hand, `Instant` is a basic class, and `OffsetDateTime` is more flexible such as various formatting patterns when generating `String` object to represent its value.
Using java.time
The modern approach in Java uses the java.time classes. This industry-leading framework supplanted the terribly troublesome old date-time classes such as Date, Calendar, and SimpleDateFormat.
DateTimeFormatter
Parse your input string. Define a formatting pattern to match.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuuMMddHHmm" ) ;
String input = "201801011000" ;
LocalDateTime
Parse as a LocalDateTime because your input lacks an indicator for time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Lacking a zone or offset means this does not represent a moment, is not a point on the timeline. Instead, this represents potential moments along a range of about 26-27 hours, the range of time zones around the globe.
OffsetDateTime
If you know for certain that this date and time-of-day were intended to represent a moment in UTC, apply the constant ZoneOffset.UTC to get an OffsetDateTime object.
OffsetDateTime odt = ldt.atOffset( ZoneOffset.UTC ) ;
ZonedDateTime
Your Question is vague. It sounds like you might know of an specific time zone intended for this input. If so, assign a ZoneId to get a ZonedDateTime object.
Understand that an offset-from-UTC is but a mere number of hours, minutes, and seconds. Nothing more, nothing less. In contrast, a time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a certain region.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
Instant
A quick way to adjust back into UTC is to extract a Instant object. An Instant is always in UTC.
Instant instan = zdt.toInstant() ;
ISO 8601
Tip: Instead of using custom format for exchanging date-time values as text, use only the standard ISO 8601 formats. The standard formats are practical, easy to parse by machine, easy to read by humans across cultures.
The java.time classes use the ISO 8601 formats by default when parsing/generating strings. The ZonedDateTime::toString method wisely extends the standard to append the name of the zone in square brackets.
Instant instant = Instant.parse( "2018-07-23T16:18:54Z" ) ; // `Z` on the end means UTC, pronounced “Zulu”.
String output = instant.toString() ; // 2018-07-23T16:18:54Z
And always include the offset and time zone in your string. Omitting the offset/zone for a moment is like omitting the currency for a price: All you have left is an ambiguous number worth nothing. Actually, worse than nothing as it can cause all sorts of confusion and errors.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
In my project have function for convert datestring local time to UTC,
function getDateInUTC(dateString) {
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm").setTimeZone(java.util.TimeZone.getTimeZone("UTC")).format(new java.text.SimpleDateFormat("yyyyMMddHHmm").setTimeZone(java.util.TimeZone.getTimeZone("CET")).parse(dateString));
}
Enjoy :)
You should use the latest classes java.time provided from Java8.
Steps are as follows:
Step-1. Parse String to LocalDateTime
Step-2. Convert LocalDateTime to the ZonedDateTime and then we can convert between different timezone.
Hope this help:
In Mirth you can write as:
String str = "201207011000";
var date_in_utc =java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")
.format(java.time.ZonedDateTime.of(java.time.LocalDateTime
.parse(str,java.time.format.DateTimeFormatter
.ofPattern("yyyyMMddHHmm")),java.time.ZoneId.of("CET"))
.withZoneSameInstant(java.time.ZoneOffset.UTC));
Full Snippet:
ZoneId cet = ZoneId.of("CET");
String str = "201207011000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmm");
LocalDateTime localtDateAndTime = LocalDateTime.parse(str, formatter);
ZonedDateTime dateAndTimeInCET = ZonedDateTime.of(localtDateAndTime, cet );
System.out.println("Current date and time in a CET timezone : " + dateAndTimeInCET);
ZonedDateTime utcDate = dateAndTimeInCET.withZoneSameInstant(ZoneOffset.UTC);
System.out.println("Current date and time in UTC : " + utcDate);
System.out.println("Current date and time in UTC : " + DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm").format(utcDate));
Give this a shout
var d = DateUtil.getDate("yyyyMMddHHmm", "201801011000");
var utcD = new Date(d).toISOString();
edit: Info on .toISOString() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

Wrong in Converting from Gregorian to Hijri Date (Android Studio)

I am developing an app that needs Hijri Date, I used what was published here converting gregorian to hijri date .
It works for me but it gave wrong date for example when the Gregorian is 20/9/2016 it became 17/12/1437 IN Hijri, and that's wrong it should be 19/12/1437.
Where is the problem ?
Regarding your conversion example, it seems to me you are looking for the Umalqura-variant of Hijri-calendar which is the official calendar of Saudi-Arabia.
The SO-link you posted refers to Joda-Time. This library does not support umalqura but four algorithmic variants of Hijri-calendar (only suitable as approximation). I have tested all four supported variants. None is for you.
Chronology iso = ISOChronology.getInstanceUTC();
Chronology hijri =
IslamicChronology.getInstance(DateTimeZone.UTC, IslamicChronology.LEAP_YEAR_INDIAN);
LocalDate todayIso = new LocalDate(2016, 9, 20, iso);
LocalDate todayHijri = new LocalDate(todayIso.toDateTimeAtStartOfDay(), hijri);
System.out.println("joda=" + todayHijri);
// LEAP_YEAR_15_BASED => 1437-12-16
// LEAP_YEAR_16_BASED => 1437-12-16
// LEAP_YEAR_HABASH_AL_HASIB => 1437-12-17
// LEAP_YEAR_INDIAN => 1437-12-17
If you are operating on Java-8-platform then you can use the following solution. However, if you are on Android and try to use the backport ThreetenABP then that will fail because its implementation deviates from Java-8:
HijrahDate hd = HijrahDate.from(LocalDate.of(2016, 9, 20));
System.out.println("java.time=" + hd); // Hijrah-umalqura AH 1437-12-19
If you want more calendar features like other variants or variable start of day (islamic days start at sunset!) or if you are operating on Android then you can use my library Time4J/A. The HijriCalendar of Time4J (or Time4A on Android) yields what you want:
System.out.println(
PlainDate.of(2016, 9, 20)
.transform(HijriCalendar.class, HijriCalendar.VARIANT_UMALQURA));
// AH-1437-12-19[islamic-umalqura]
Note that the last example is a conversion valid at noon time. When using evening as start of day then please consult the javadoc how to do that.
Update from 2016-09-07:
Other possible umalqura solutions with very different APIs on Android include
Android developer preview 24 (Google seems to begin to include ICU4J)
Calendar-adaptation of msarhan (thanks to comment of OP, this library supports two languages arabic and english for month names)

Grails: how to parse date.toString() without making a custom formatter?

I have a Grails application that needs to parse Dates out of strings that were created with the date.toString() method.
My system's default date.toString() format is "Thu Apr 20 00:27:00 CEST 2006" so I know I can turn a Date into a string and then back into an object using Date.parse('EEE MMM dd HH:mm:ss z yyyy', new Date().toString()).
But that's lame! I shouldn't have to reverse engineer the system's default date format. Plus, I'm not sure under what circumstances the default date format can change, thus breaking that code.
Is there a way to parse a date.toString() back into a Date without using a hand-rolled formatter like that?
Thanks!
Update: I filed this Jira ticket to get such a feature added Groovy. Someone commented on the ticket that Java's date.toString() method is hard-coded to use EEE MMM dd HH:mm:ss z yyyy. That sucks for Java to be so inflexible, but it makes it easier for me to live with hard-coding the formatter!
There's a page over here showing how bad this is in Java (and hence in Groovy)
I agree that there should be a Date.parse method in Groovy which uses this default Date.toString() format.
Maybe it's worth adding a request for improvement over on the Groovy JIRA?
As a temporary workaround, you could add your parse method to the String metaClass in Bootstrap.groovy?
String.metaClass.parseToStringDate = { Date.parse( 'EEE MMM dd HH:mm:ss z yyyy', delegate ) }
Then you can do:
new Date().toString().parseToStringDate()
anywhere in the groovy portions of your grails app
I haven't worked with Grails and I know this is not the answer to your question, but as a workaround, couldn't you just save the format-string as a global variable?
if u use it to convert to json, maybe code below could help:
//bootstrap
JSON.registerObjectMarshaller(Date) {
return it?.format("yyyy-MM-dd HH:mm:ss")
}