Time Formatting Parsing in Minitab
Java supports time formatting and parsing via pattern-based layouts, similar to other programming languages. We’ll use the java.time
package for this example.
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
public class TimeFormattingParsing {
public static void main(String[] args) {
// Here's a basic example of formatting a time
// according to ISO_DATE_TIME, which is similar to RFC3339
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now.format(DateTimeFormatter.ISO_DATE_TIME));
// Time parsing uses the same DateTimeFormatter as formatting
ZonedDateTime t1 = ZonedDateTime.parse("2012-11-01T22:08:41+00:00", DateTimeFormatter.ISO_DATE_TIME);
System.out.println(t1);
// We can use predefined formatters or create custom ones
System.out.println(now.format(DateTimeFormatter.ofPattern("h:mma")));
System.out.println(now.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL)));
System.out.println(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX")));
// Parsing with custom format
String customFormat = "h mm a";
LocalDateTime t2 = LocalDateTime.parse("8 41 PM", DateTimeFormatter.ofPattern(customFormat));
System.out.println(t2);
// For purely numeric representations you can also
// use standard string formatting with the extracted
// components of the time value
System.out.printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
now.getYear(), now.getMonthValue(), now.getDayOfMonth(),
now.getHour(), now.getMinute(), now.getSecond());
// DateTimeParseException will be thrown on malformed input
try {
ZonedDateTime.parse("8:41PM", DateTimeFormatter.RFC_1123_DATE_TIME);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
In Java, we use the java.time
package for date and time operations. The DateTimeFormatter
class is used for parsing and formatting dates and times.
We start by getting the current time using ZonedDateTime.now()
and formatting it using the ISO_DATE_TIME formatter, which is similar to RFC3339.
For parsing, we use the same DateTimeFormatter
with the parse
method of ZonedDateTime
.
Java provides several predefined formatters, and we can also create custom ones using patterns. The ofPattern
method allows us to define custom formats.
For purely numeric representations, we can use String.format
or System.out.printf
with the extracted components of the time value.
When parsing fails due to malformed input, Java throws a DateTimeParseException
. We catch this exception to demonstrate error handling.
To run this program, save it as TimeFormattingParsing.java
, compile it with javac TimeFormattingParsing.java
, and run it with java TimeFormattingParsing
. The output will show various formatted dates and times, along with examples of parsing.