简体   繁体   中英

Parse negative time String in java

I have a selenium script to compare the negative and positive time say -01:07 and positive format +00:34 and +00:00 which are in String format. I want to parse this time in negative time or positive time as per the + or - sign and want to compare whether its after or before with negative

At the moment I am doing like this

Date late = (Date) format.parse("05:00");
Date ontime = (Date) format.parse("00:00");
Date early = (Date) format.parse("00:59");

SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String myTime = propertyConfig.getString("myTime");
//Here myTime = -00:47
org.junit.Assert.assertTrue(format.parse(myTime).after(early) && format.parse(myTime).before(late));

I am not sure whether we can do it in java to parse a negative time. Can some one help on this?

Thanks

I don't believe you can do that directly as your trying, you will have to do some manual parsing of the String and then perform some operations. I would recommend using the JodaTime library for your date/time manipulation needs and it provides alot of useful functionality that the standard Date classes don't.

A particularly useful function for you would be in the DateTime class where there are are methods to add and subtract units of time (years, minutes, seconds, etc..)

http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html

In your code, you can look at the first character in your string to determine if your going to add or subtract. Then extract the time measurments from that string and pass that into the appropriate add/subtract methods of the DateTime class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM