Last active
July 20, 2016 12:47
-
-
Save MenoData/ce38ede895995012013dd4a7b754e8cd to your computer and use it in GitHub Desktop.
How to print a date with or without offset?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Locale; | |
import net.time4j.PlainDate; | |
import net.time4j.format.expert.ChronoFormatter; | |
import net.time4j.format.expert.PatternType; | |
import net.time4j.tz.OffsetSign; | |
import net.time4j.tz.ZonalOffset; | |
/** | |
* Demonstrates how to print plain calendar dates with timezone offset. | |
* | |
* Following examples use optional format sections. | |
* | |
* Without any special action, optional format sections are only optional | |
* during parsing, but not during printing. However, to specifiy an optional | |
* printing section, users can specify a special printing condition | |
* telling Time4J when to suppress printing. | |
*/ | |
public class PrintingDateWithOffset { | |
public static void main(String... args) { | |
// first example: date without offset, the formatter throws the expected exception | |
try { | |
ChronoFormatter<PlainDate> f1 = | |
ChronoFormatter.ofDatePattern("uuuuMMdd[XX]", PatternType.CLDR, Locale.ROOT); | |
f1.format(PlainDate.of(2016, 7, 20)); | |
} catch (IllegalArgumentException iae) { | |
System.out.println(iae.getMessage()); // Cannot extract timezone offset from format attributes for: 2016-07-20 | |
} | |
// second example: remember that a calendar date has no offset, hence the offset must be explicitly specified | |
ChronoFormatter<PlainDate> f2 = | |
ChronoFormatter.ofDatePattern("uuuuMMdd[XX]", PatternType.CLDR, Locale.ROOT) | |
.withTimezone(ZonalOffset.ofHoursMinutes(OffsetSign.AHEAD_OF_UTC, 5, 30)); | |
System.out.println(f2.format(PlainDate.of(2016, 7, 20))); // 20160720+0530 | |
// third example: does not make much sense, just for explaining the usage of an optional printing section | |
// However, such a formatter could be useful if users write a specialized date chronology with optional offset | |
// for modelling XML-type xsd:date | |
ChronoFormatter<PlainDate> f3 = | |
ChronoFormatter.setUp(PlainDate.axis(), Locale.ROOT) | |
.addPattern("uuuuMMdd", PatternType.CLDR) | |
.startOptionalSection(d -> d.hasTimezone()) // only printing when date has offset (never true) | |
.addTimezoneOffset() | |
.endSection() | |
.build() | |
.withTimezone(ZonalOffset.ofHoursMinutes(OffsetSign.AHEAD_OF_UTC, 5, 30) // unused, see print condition above | |
); | |
System.out.println(f3.format(PlainDate.of(2016, 7, 20))); // 20160720 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment