我想从字符串中获取的日期打印时间(小时:分钟:秒)。
我有一个包含下一个值的字符串:
String dateStr = "Tue, 04 Aug 2015 12:09:10 GMT"
我将其解析为日期:
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
Date d = format.parse(dateStr);
但是当我尝试获得小时,分钟和秒时,我得到了不同的值:
System.out.println("The current time is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
打印:"当前时间是:9:9:10"
什么错了?不打印"当前时间是:12:9:10"?
谢谢:)
更多信息:
当我创建日期时,它会自动将时区设置为GMT-03:00 2015,这就是为什么打印时间减少3小时的原因。我该如何设置时区?
答案 0 :(得分:2)
试试这个,你会得到它
try {
String dateStr = "Tue, 04 Aug 2015 12:09:10 GMT";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy hh:mm:ss",Locale.getDefault());
SimpleDateFormat formatTarget = new SimpleDateFormat("hh:mm:ss",Locale.getDefault());
System.out.println("time " + formatTarget.format(format.parse(dateStr)));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 1 :(得分:1)
public static void main(String[] args) throws ParseException {
String dateStr = "Tue, 04 Aug 2015 12:09:10 GMT";
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.ENGLISH);
Date d = format.parse(dateStr);
System.out.println("The current time is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"), Locale.ENGLISH);
cal.setTime(d);
System.out.println("The current time is: " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND));
}
答案 2 :(得分:0)
唯一的方法是从字符串源中删除GMT
。因为这表明您想使用时区进行解析。之后,您必须删除zzz
,例如:
String dateStr = "Tue, 04 Aug 2015 12:09:10"
SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.ENGLISH);
Date d = format.parse(dateStr);
System.out.println("The current time is: " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds());
答案 3 :(得分:-1)
用于打印当前时间你可以使用这种方法
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
int minutes=c.get(Calendar.MINUTE);
int hour=c.get(Calendar.HOUR);
int noon=c.get(Calendar.AM_PM);
int day=c.get(Calendar.DAY_OF_WEEK);
int date=c.get(Calendar.DATE);
int month=c.get(Calendar.MONTH)+1;
int year=c.get(Calendar.YEAR);
String currentTime =“当前时间是:”+ String.valueOf(小时)+“:”+ String.valueOf(分钟)+“:”String.valueOf(秒);
此外,您可以使用此日历中的日年月等