您的位置:首页 > 编程语言 > Java开发

JAVA学习15_Java 中与时间有关的几个问题

2016-04-26 19:51 731 查看
1. Date

# 需要说明的是 Date 无时区,

# 但date.toString() 则是按当前 JVM 的默认时区来格式化的,也就是 TimeZone.getDefault() 获得的时区,

# 同时 date.toString() 是按照 "EEE MMM dd HH:mm:ss zzz yyyy" 来格式化的;

2. Date to String

Java代码


SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

String strDate = format.format(date);

3. String to Date

Java代码


SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Date date = format.parse(strDate);

4. 时区转换

Java代码


String strDate = "2013-07-17 10:12:15";

String fromTimeZone = "GMT+8";

String toTimeZone = "GMT+0";

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

format.setTimeZone(TimeZone.getTimeZone(fromTimeZone));

Date date = format.parse(strDate);

format.setTimeZone(TimeZone.getTimeZone(toTimeZone));

strDate = format.format(date);

System.out.println(strDate);

5. 区域问题(不同的区域对时间的显示是不同的)

Java代码


SimpleDateFormat format1 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.SIMPLIFIED_CHINESE);

SimpleDateFormat format2 = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

System.out.println(format1.format(new Date())); // 星期三 七月 17 10:57:50 CST 2013

System.out.println(format2.format(new Date())); // Wed Jul 17 10:57:50 CST 2013

6. 时间跳变

# 1582-10-04 的下一天是 1582-10-15

Java代码


Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.YEAR, 1582);

calendar.set(Calendar.MONTH, 9);

calendar.set(Calendar.DAY_OF_MONTH, 4);

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

System.out.println(format.format(calendar.getTime())); // 1582-10-04

calendar.add(Calendar.DAY_OF_MONTH, 1); // 增加一天

System.out.println(format.format(calendar.getTime())); // 1582-10-15

# 参见:http://dlc.sun.com.edgesuite.net/jdk/jdk-api-localizations/jdk-api-zh-cn/builds/latest/html/zh_CN/api/java/util/GregorianCalendar.html

# 夏令时

Java代码


Calendar calendar = Calendar.getInstance();

calendar.set(Calendar.YEAR, 1986);

calendar.set(Calendar.MONTH, 4);

calendar.set(Calendar.DAY_OF_MONTH, 3);

calendar.set(Calendar.HOUR_OF_DAY, 23);

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

System.out.println(format.format(calendar.getTime())); // 1986-05-03 23:46:38

calendar.add(Calendar.HOUR_OF_DAY, 1); // 增加一个小时

System.out.println(format.format(calendar.getTime())); // 1986-05-04 01:46:38(中间跳过了 00:46:38)

# 参见:http://baike.baidu.com/view/100246.htm

7. 设置 JVM 的时区

# 在JVM启动的时候,加入参数-Duser.timezone=GMT+08

# GMT, UTC 和 CST 时间的区别

# GMT 代表格林尼治标准时间;

# UTC 是比 GMT 更加精确的世界时间标准,在不需要精确到秒的情况下,通常也将GMT和UTC视作等同;

# CST 可以同时表示中国、美国、澳大利亚、古巴四个国家的标准时间;

# 参见:

#/article/4676630.html

#http://baike.baidu.com/view/42936.htm

原文来自:http://dyccsxg.iteye.com/blog/1908607
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: