AKWARD AKWARD - 2 months ago 5
Java Question

read time from text file in java

I am trying to write some codes in java to read a text file, but when it read a time in (hh:mm) formate as example below:

6:30 14:30

and there is my java code to convert the string to Data formate

DateFormat formatter = new SimpleDateFormat("hh:mm");
strLine = br.readLine();
strLine = strLine.trim();
tokens2 = strLine.split(" ");

the output will be:

Thu Jan 01 06:30:00 AST 1970

it will give in long formate Date , While I want just take timezone(06:30).
what should I do ?
Any advice.

edit: the problem solved by Joda time by this code:


it is just take time


Firstly, your time pattern is wrong - you should be using HH:mm as you're using a 24-hour clock in your examples.

Secondly, you're parsing a Date. A Date is just an instant in time: it doesn't know about the time zone, calendar, whether you're interested in just the time, just the date etc.

Thirdly, you're seeing that output because you're basically just calling Date.toString().

There's no type in Java to represent just "a time of day" (which isn't at all the same as a time zone, by the way). You could format a Date to just include the time part, but if you want to do that, I'd strongly recommend using a time zone of UTC to avoid any possible DST problems.

A better solution would be to use Joda Time which has a LocalTime type - ideal for your situation. You can parse that (DateTimeFormatter.parseLocalTime) and then work with it appropriately, formatting it (again to just a time) whenever you want.