开发者

Parsing time string with SimpleDateFormat

I have a problem parsing just the time string from my database

private static final String TIME_FORMAT = "HH:mm:ss";
public static final SimpleDateFormat timeFormat = new SimpleD开发者_如何转开发ateFormat(TIME_FORMAT, Locale.getDefault());

And following the output:

String time = "17:17:57";
Date myParsedDate = timeFormat.parse(time); //forget the exception thing
//output of myParsedDate.toString = "Thu Jan 01 16:47:57 GMT+08:00 1970"

It seems as though theres a problem with the locale or something.. just a simple string.. Why is this so? i just want the date to be the having the time i need for my time picker.. gee..

Edit Because i am using a static time format i decided to use my little helper method

public static Date getTimeFromTimeString(String timeString)
{
    String[] splitStrings = timeString.split(":");

    Date timeDate = new Date();
    timeDate.setHours(Integer.parseInt(splitStrings[0]));
    timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
    timeDate.setSeconds(Integer.parseInt(splitStrings[2]));

    return timeDate;
}

Thanks for the help Jon Skeet.. I believe it is the TimeZone offset that is causing this.. .. ill just stick to my little method..


The problem is you're printing out the result of Date.toString() - which always shows the results in the system time zone. That's probably not what you want.

The Date itself has no concept of a time zone - it's just an instant in time.

I would suggest you use Joda Time if at all possible. That has a LocalTime which actually represents what you're parsing here.

EDIT: Just to reiterate what's in the comment... I suspect that the time zone in your DateFormat is not the same as the time zone used by Date.toString. For simplicity, it's probably worth setting the DateFormat's time zone to UTC, and then if you want to convert to a Calendar you should set that time zone to UTC as well before calling setTime(date).


Just do this:

 Calendar c = Calendar.getInstance();
 c.setTime(myParsedDate);

 int hours = c.get(Calendar.HOUR);
 int mins = c.get(Calendar.MINUTE);
 int seconds = c.get(Calendar.SECOND);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜