Display and save only hours in int

陌路散爱 提交于 2020-01-11 07:59:08

问题


How to display only hours and using int variable? I mean print time like 20:30:44 PM, I want to store only hours, mean 20 in int variable. how to do that?

Can anybody tell me the code if you know, thanks?


回答1:


Try using Calendar's get method like:

 Calendar c = ..
 c.setTime(...);//if you have time in long coming from somewhere else
 int hour = c.get(Calendar.HOUR_OF_DAY);



回答2:


If you try to parse time from String I recommend these solutions:

String time = "20:30:44 PM"; // this is your input string
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss aa");

try {
    Date date = sdf.parse(time);

    // this is the uglier solution
    System.out.println("The hour is: "+date.getHours());

    GregorianCalendar gc = new GregorianCalendar();
    gc.setTime(date);

    // this is nicer solution
    System.out.println("The hour is: "+gc.get(Calendar.HOUR_OF_DAY));

} catch (ParseException e) {
    System.err.println("Couldn't parse string! "+e.getMessage());
}

date.getHours() and gc.get(Calendar.HOUR_OF_DAY) return int, in this example I printed it out without creating variable.

You can, of course, use regular expression to find out hour in your string but above solutions should do the trick. You can learn more about SimpleDateFormat and available patterns here. I hope I helped you a bit.

EDIT: In his comment autor noted, that date isn't static (like in String) but dynamic:

Calendar calendar = new GregorianCalendar();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
System.out.println("The hour is: "+hour);

I hope this helps.



来源:https://stackoverflow.com/questions/28796710/display-and-save-only-hours-in-int

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!