voivoda
voivoda

Reputation: 21

Groovy - String to Time

I have a String like this:

String timeString = "2230"

And I want to convert it into Time type.

I have tried to use this

def bookingTime = new Date().parse("2230")

But it doesn't work. Any ideas?

Thank you for the help!

Upvotes: 2

Views: 4697

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 340350

I do not know Groovy well, but I assume it does not have its own libraries, at least for date-time work. So this answer is aimed at Java libraries.

Date-Time versus Time-Of-Day

I want to convert it into Time type.

Apparently you want to represent only a time-of-day without any date or time zone.

The java.util.Date/.Calendar classes bundled with Java represent a combination of date and time-of-day. (By the way, these classes are notoriously troublesome, confusing, and flawed. Avoid them.)

So, Java 7 and earlier has no "Time" type. Java has had a java.sql.Time, but this class is a hack. A .Time is a j.u.Date with its date portion set to first day of 1970 UTC (the epoch). This class is only intended for use with databases and JDBC, and even then is supplanted by java.time (see below).

Instead you should use either:

  • Joda-Time library
  • java.time package (built into Java 8, inspired by Joda-Time, defined by JSR 310)

Both of these libraries offer a LocalTime class (Joda-Time, java.time) to represent a time-only value without date and without time zone.

Joda-Time

Some example code in Joda-Time 2.5, using Java syntax rather than Groovy.

If your input string had colons it would follow standard ISO 8601 format. The standard formats are used in both Joda-Time and java.time by default for parsing and generating strings.

LocalTime localTime = LocalTime.parse( "18:55" );  // ISO 8601 format used by default.
System.out.println( "localTime: " + localTime );  // localTime: 18:55:00.000

With your non-standard format, you must specify a formatter.

LocalTime localTime2 = DateTimeFormat.forPattern( "HHmm" ).parseLocalTime( "2230" );
System.out.println( "localTime2: " + localTime2 );  // localTime2: 22:30:00.000

Upvotes: 0

Opal
Opal

Reputation: 84904

Try (Groovy implementation):

String timeString = "2230"
def bookingTime = Date.parse("HHmm", timeString)

Upvotes: 5

Related Questions