当前位置: 移动技术网 > IT编程>开发语言>Java > 基于java时区转换夏令时的问题及解决方法

基于java时区转换夏令时的问题及解决方法

2019年07月19日  | 移动技术网IT编程  | 我要评论

快乐大本营花样少男少女,短跑名将和歼10百米赛,纺织皮革

一.准备知识

1.america/new_york的夏令时时间如下: 包左不包右

2016-3-13, 02:00:00到2016-11-6, 02:00:00 

2017-3-12, 02:00:00到2017-11-5, 02:00:00

2.三字母时区 id

为了与 jdk 1.1.x 兼容,一些三字母时区 id(比如 "pst"、"ctt"、"ast")也受支持。

但是,它们的使用被废弃,这是因为相同的缩写经常用于多个时区

例如 cst:有4个意思,美国,澳大利亚,中国,古巴时间

3.标准

gmt:green mean time格林威治标准时间,1960年前被作为标准时间参考 gmt+12-->gmt-12

java8的范围为gmt+18-->gmt-18

utc:coordinated universal time 时间协调世界时间 ,比gmt精确,在1972年1月1日成为新的标准;utc,utc+1,utc+2...utc+12,utc-12...utc-1

java8的范围 utc-18-->utc+18

dst:daylight saving time 夏令时间,指在夏天的时候,将时钟拨快一个小时,以提早日光的使用,在英国称为夏令时间;

目前有110多个国家采用夏令时;

在中国,从1986-1992只实行了6年,之后就取消了;原因如下:

1.中国东西方向跨度很大,而且采用的是统一的东八区,采用夏令时无法兼容东西部;

2.高纬度地区,冬夏昼夜时间变化大;意义不大;

4.表示东八区可以用 : gmt+8或者etc/gmt-8(刚好相反,为什么呢,因为php开发者认为,东八区比标准时间快8小时,应该减去8小时,于是表示成了这样。参考的对象不同导致了不同的表示方法;)

5. 中国时区的表示方式

gmt+8
utc+8
asia/harbin 哈尔滨 //中国标准时间
asia/chongqing 重庆//中国标准时间
asia/chungking 重庆//中国标准时间
asia/urumqi 乌鲁木齐//中国标准时间
asia/shanghai 上海(东8区)//中国标准时间
prc
asia/macao 澳门 //中国标准时间
hongkong 香港 //香港时间跟中国标准时间一致
asia/hong_kong 香港
asia/taipei 台北(台湾的) //中国标准时间
新加坡跟中国的时间一样;
asia/singapore
singapore

6. 标准时区的表示

utc
utc+0
utc-0
gmt 格林尼治标准时间
gmt0 格林尼治标准时间
etc/gmt 格林尼治标准时间
etc/gmt+0 格林尼治标准时间
etc/gmt-0 格林尼治标准时间
etc/gmt0 格林尼治标准时间
注意:gmt+xx(-xx)有很大的包容性,还可以自动的识别各种时间的表示

二. 时区转换

环境:java8之前

1.将当前时间转换为指定时区显示

@test 
public void test() throws exception { 
 date a=new date(); 
 simpledateformat sf = new simpledateformat("yyyy-mm-dd hh:mm:ss"); 
 sf.settimezone(timezone.gettimezone("america/new_york")); 
 //把中国时区转为了美国纽约时区 
 system.out.println(sf.format(a)); 
} 

2.指定时间转为指定时区显示

真能正确转换吗?好像有个坑,看了看网上的实现

关于夏令时,感觉有点问题

//实现方式1 没有考虑夏令时 
 @test 
public void test2() throws exception { 
/  date datetime=new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 14:00:00"); 
 date datetime=new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-10-6 14:00:00"); 
 timezone zhong = timezone.gettimezone("gmt+8:00");//中国 
 timezone york = timezone.gettimezone("america/new_york"); //gmt-5 
 //这里的时区偏移量是固定的,没有夏令时,错 
 long chinesemills = datetime.gettime() + york.getrawoffset()-zhong.getrawoffset(); 
 date date = new date(chinesemills); 
 system.out.println(new simpledateformat("yyyy-mm-dd hh:mm:ss").format(date)); 
} 
 //实现方式2 你可能回想,用calendar类的calendar.dst_offset
 //还是不对calendar.dst_offset这个是死的
	@test
	public void test3() throws exception {

//		date time =new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 14:00:00");
//		date time =new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 1:00:00");
//		date time =new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 0:59:00");
//		date time =new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 1:59:59");
		date time =new simpledateformat("yyyy-mm-dd hh:mm:ss").parse("2016-11-6 3:00:00");
	
		// 1、取得本地时间:
		calendar cal = calendar.getinstance();
		cal.settime(time);
		cal.settimezone(timezone.gettimezone("america/new_york"));
		// 2、取得时间偏移量:这个是固定的
		int zoneoffset = cal.get(calendar.zone_offset)/(1000*60*60);
		// 3、取得夏令时差:这个是固定的,不是根据时间动态判断,只要时区存在夏令时,就是1
		int dstoffset = cal.get(calendar.dst_offset)/(1000*60*60);
		
		system.out.println(zoneoffset);
		system.out.println(dstoffset);
		// 4、从本地时间里扣除这些差量,即可以取得utc时间:
//		cal.add(calendar.millisecond, -(zoneoffset + dstoffset));
		cal.add(calendar.hour, -(zoneoffset + dstoffset));
		date time2 = cal.gettime();
		system.out.println(new simpledateformat("yyyy-mm-dd hh:mm:ss").format(time2));
		}
//实现方式3 

准备工作 
  // 不是说java会自动替我们处理夏令时吗
	//先来个简单的测试,看夏令时判断方法是否是正确,就可以推断,java的自动处理是否正确
	//已知2016年:america/new_york的夏令时时间是: 2016-3-13 02:00:00 到 2016-11-06 01:59:59 
  @test
 	public void test4() throws exception {
 	//转换为0时区时间作为参照点
 	simpledateformat sf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
 	sf.settimezone(timezone.gettimezone("gmt+0"));
//  	date datetime=sf.parse("2016-11-6 5:59:59");
 	date d1=sf.parse("2016-03-13 6:59:59");//false 
  	date d2=sf.parse("2016-03-13 7:00:00");//true 
  	date d3=sf.parse("2016-11-6 6:59:59");//false 
  	date d4=sf.parse("2016-11-6 7:00:00");//false
  	//现在发现了,对于夏令时开始的时间判断确实没问题,但是对于夏令时的结束时间判断错误,准确说,提前了一个小时判断了
  	//看下面验证就知道了,那么为什么提前了一个小时,不知道,怎么解决? 目前想到的只能用java8
  d3=sf.parse("2016-11-6 5:59:59");//true 
  d4=sf.parse("2016-11-6 6:00:00");//false 
  timezone york = timezone.gettimezone("america/new_york"); //gmt-5
  	
  system.out.println("目标时区是否使用了夏令时:"+isdaylight(york, d1));
  system.out.println("目标时区是否使用了夏令时:"+isdaylight(york, d2));
  system.out.println("目标时区是否使用了夏令时:"+isdaylight(york, d3));
  system.out.println("目标时区是否使用了夏令时:"+isdaylight(york, d4));
 	}
 
 //判断是否在夏令时
 private boolean isdaylight(timezone zone,date date) {
		return zone.usedaylighttime()&&zone.indaylighttime(date);
 }
 //实现方式3 
 //通过上面的验证我们知道了系统的判断是有问题的,通过设置时区,程序自动处理夏令时也不是那么正确,起码我现在无法理解为什么
  @test
	public void test5() throws exception {
 	//中间相隔13个小时  中国+8 纽约-5
 	changezone("2016-3-13 14:59:59", "prc","america/new_york", "yyyy-mm-dd hh:mm:ss");//2016-03-13 01:59:59
 	changezone("2016-3-13 15:00:00", "prc","america/new_york", "yyyy-mm-dd hh:mm:ss");//2016-03-13 03:00:00
 	changezone("2016-11-6 13:59:59", "prc","america/new_york", "yyyy-mm-dd hh:mm:ss");//2016-11-06 01:59:59
  //这个结果是不对的,应该02:00:00
  changezone("2016-11-6 14:00:00", "prc","america/new_york", "yyyy-mm-dd hh:mm:ss");//2016-11-06 01:00:00
 }
 	//具体的实现如下:
 //思路是没问题的
 public static void changezone(string time, string srcid, string destid,
 	 string pattern) throws parseexception {
 	 //设置默认时区
   timezone zone = timezone.gettimezone(srcid);
 	 timezone.setdefault(zone);
 	 date date = new simpledateformat(pattern).parse(time);
 	//设置目标时区
 	timezone destzone = timezone.gettimezone(destid);
 	simpledateformat sdf = new simpledateformat(pattern);
 	//设置要格式化的时区
 	sdf.settimezone(destzone);
 	string changtime = sdf.format(date);
 	// 获取目标时区
 	system.out.println("修改时区后" + destzone.getid() + "的时间:" + changtime);
  }

小结:以上的三种实现方式得到的结果对夏令时都有点问题

三,java8的实现

1.先看看java8的支持时区变化

//jdk8的可用时区
	@test
	public void testname1() throws exception {
		//jdk8的所有时区
		set<string> ids = zoneid.getavailablezoneids();
		string[] id1 = ids.toarray(new string[ids.size()]);
		string idss = arrays.tostring(id1).replace("]", ",]");
		
		system.out.println(ids.size());//少了28个 595
		
		//jdk8之前的所有时区
		string[] id2 = timezone.getavailableids();
		system.out.println(id2.length); //623
	
		//找出没jdk8中没有的
		for (string id : id2) {
			if (!idss.contains(id+",")) {
				system.out.print(id+",");
			}
		}
		
		//结论:jdk8里面的所有时区,在之前 全部都有
		//jdk8删除的时区如下:
		//都是一些容易引起歧义的时区表示方法
//		 est, hst, mst, act, aet, agt, art, ast, bet, bst, cat, cnt, cst, ctt, eat, ect, iet, ist, jst, mit, net, nst, plt, pnt, prt, pst, sst, vst,
		
		// 但是这些短名称的其实还是可以使用的,只是支持列表里面没有了而已
		localdatetime date = localdatetime.ofinstant(instant.now(),
				zoneid.of(zoneid.short_ids.get("pst")));
		system.out.println("\ndate = " + date);
		
	}

2.如何添加时区信息呢,或者说转换

//localdate,localdatetime,instant添加时区信息
	@test
	public void testname3() {
		localdate date=localdate.now();
		//localdate添加时区信息
		//方式1
		zoneddatetime zone = date.atstartofday(zoneid.of("gmt+08:00"));
		system.out.println(zone);
		zone = date.atstartofday(zoneid.systemdefault()); 
		system.out.println(zone);
		//方式2
	 localdate date2 = localdate.now(zoneid.of("gmt+0"));
		system.out.println(date2);
		
		system.out.println("------------------------------------");
		//localdatetime添加时区信息
		localdatetime time = localdatetime.now();
		//方式1
		zoneddatetime zonetime = time.atzone(zoneid.of("gmt+0"));
		//方式2
		zoneddatetime zonetime2=zoneddatetime.now(zoneid.of("gmt+0"));
		//方式3
		localdatetime zonetime3 = localdatetime.now(clock.system(zoneid.of("gmt+0")));
		//方式4
		zoneddatetime zonetime4 = zoneddatetime.of(time, zoneid.of("gmt+0"));
		system.out.println(zonetime); //不变
		system.out.println(zonetime2);//变
		system.out.println(zonetime3);//变
		system.out.println(zonetime4);//不变
		
		system.out.println("------------------------------------");
		
		//instant时区信息
		zoneddatetime atzone = instant.now().atzone(zoneid.of("gmt+0"));
		system.out.println(atzone);//变
		
	}

3.如何获取当前时间的指定时间(测试略)

 //获取当前时间的指定时区时间,参照点:0时区
		public localdatetime getcurrentzonetime(zoneid dest) {
			 objects.requirenonnull(dest);
			 localdatetime time2 = localdatetime.now(clock.system(dest));
			 
			 string zonedesc = getzonedesc(timezone.gettimezone(dest));
			 system.out.println(dest.getid()+"对应得标准时区:"+zonedesc);
			 system.out.println("目标时区"+dest+"的时间"+time2.format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss")));
			 return time2;
		}
//获取标准时区,方式1
		//在jdk8之前的方法,利用timezone
	 private static string getzonedesc(timezone destzone) {
	 	objects.requirenonnull(destzone);
		 int offset = destzone.getrawoffset() / (1000 * 60 * 60);
		 if (offset <= 0) {
			return "gmt"+string.valueof(offset);
		 } else {
			return "gmt+" + string.valueof(offset);
		 }
	 }
 //java8的方法,方式2,利用zonerules
	 //得到时区的标准偏移量,zonerules.getstandardoffset
	 //得到时区的实际偏移量(得到的偏移量会根据夏令时改变) 
   // 方式1:zoneddatetime.getoffset
	 // 方式2:zonerules.getoffset
	 private string getzonedesc2(zoneid dest) {
	 	objects.requirenonnull(dest);
	 	zonerules rule=dest.getrules(); 
	 	//获取时区的标准偏移量
	 	string standardoffset = rule.getstandardoffset(zoneddatetime.now(dest).toinstant()).getid();
	 	string s = standardoffset.split(":")[0];
	 	int offset = integer.parseint(s);
	 	//返回方式1:带小时分钟
//	 	return "gmt"+standardoffset;
	 	//返回方式2:只带小时数
	 	if (offset>0) {
	 		return "gmt+"+offset;
			}else{
				return "gmt"+offset;
			}
	 }
	 

4.如何获取指定时区的指定时间

开始实现上面留下的时区问题啦

同理先看下使用java8的夏令时判断方法是否正确

  //先手写个判断美国的时间是否在夏令时
	 public boolean isdaylighttime(localdatetime a) {
   objects.requirenonnull(a);
   localdatetime startdate = a.withmonth(3).tolocaldate().attime(2, 0);
	localdatetime startlightday = startdate.with(temporaladjusters.dayofweekinmonth(2, dayofweek.sunday));
			//更新为11月
	localdatetime enddate = a.withmonth(11).tolocaldate().attime(1, 59,59);
	localdatetime endlightday = enddate.with(temporaladjusters.dayofweekinmonth(1, dayofweek.sunday));
			
	if (a.isbefore(startlightday) || a.isafter(endlightday)) {
			system.out.println("不在夏令时"+a);
			return false;
		}
			system.out.println("在夏令时"+a);
			return true;
		}
	 
	 //其实java8 已经有现成的方法啦,比我的好用
	 //传入指定时间和时区
	 public boolean isdaylighttime(localdatetime a,zoneid dest) {
	 	zoneddatetime z1 = a.atzone(dest);
	 	//或者这样转
//	 	zoneddatetime z2 = zoneddatetime.of(a, dest);
	 	system.out.println(z1.format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss")));
	 	
	  zonerules rules = dest.getrules();
	  boolean flag= rules.isdaylightsavings(z1.toinstant());
	  system.out.println(flag);
		return flag;
	 }

//测试一下,发现java8的夏令时方法判断完全正确噢

//已知2016年:america/new_york的夏令时时间是: 2016-3-13 02:00:00 到 2016-11-06 01:59:59 
//	   (每年3月的第二个星期日,11月的第一个星期日)
	 @test
		public void testname() throws exception {
//			localdatetime a1=localdatetime.now();
	 	localdatetime a2=localdatetime.of(2016, 3, 13, 1, 59,59);
			localdatetime a3=localdatetime.of(2016, 3, 13, 2, 00);
			localdatetime a4=localdatetime.of(2016, 11, 6, 1, 59,59);
			localdatetime a5=localdatetime.of(2016, 11, 6, 2, 0,0);
//			isdaylighttime(a2);
//			isdaylighttime(a3);
//			isdaylighttime(a4);
//			isdaylighttime(a5);
			
			system.out.println("=================");
			isdaylighttime(a2,zoneid.of("america/new_york"));//false
			isdaylighttime(a3,zoneid.of("america/new_york"));//true
			isdaylighttime(a4,zoneid.of("america/new_york"));//true
			isdaylighttime(a5,zoneid.of("america/new_york"));//fasle
		}

开始实现:

版本1:

//获取指定时间的 指定时区时间 参照点:默认时区 
  public localdatetime getzongtime(localdatetime time,zoneid dest) { 
   objects.requirenonnull(dest); 
   return getzongtime(time, null, dest); 
  } 
//不能用2个时区的zoneddatetime相减,因为这里一旦指定时区,那个时间就是这个时区了 
 public localdatetime getzongtime(localdatetime time,zoneid src,zoneid dest) { 
   //难点就是如何求偏移量 
  //这里使用默认时区,在中国的就是中国,在美国的就是美国,这样估计更合适 
   objects.requirenonnull(dest); 
   zoneddatetime z1=null; 
   if (src==null) { 
    z1 = time.atzone(zoneid.systemdefault()); 
   }else{ 
    z1 = time.atzone(src); 
   } 
      // 时区及时响应变化 
   zoneddatetime z2 = z1.withzonesameinstant(dest); 
   
   system.out.println(dest.getid()+"对应得标准时区:"+getzonedesc( timezone.gettimezone(dest))); 
   system.out.println("目标时区"+dest+"的时间"+z2.format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss"))); 
   system.out.println("-------------"); 
   return time; 
 } 

测试如下:

@test 
 public void test6() throws exception { 
   //预计不在夏令时 2016-03-13 01:59:59 
   localdatetime time4= localdatetime.of(2016, 3, 13, 14, 59, 59); 
   getzongtime(time4,zoneid.of("america/new_york")); 
   
   //预计在夏令时 2016-03-13 03:00:00 
   localdatetime time1= localdatetime.of(2016, 3, 13, 15, 00, 00); 
   getzongtime(time1,zoneid.of("america/new_york")); 
    
   //预计在夏令时 结果呢:2016-11-06 01:59:59 
   //感觉又失败了,应该是2016-11-06 02:59:59 
   //也就是说,此时java8对夏令时的结束处理之前的 方式3 一模一样,提前了一小时判断 
   //即把夏令时结束时间当成了2016-11-6 00:59:59,但是java8的判断方法是正确的呀,是不是有点奇怪 
   localdatetime time2= localdatetime.of(2016, 11, 6, 14, 59, 59); 
   getzongtime(time2,zoneid.of("america/new_york")); 
    //预计不在夏令时2016-11-06 02:00:00 
   localdatetime time3= localdatetime.of(2016, 11, 6, 15, 00, 00); 
   getzongtime(time3,zoneid.of("america/new_york")); 
 } 

所以我现在怀疑这种结果到底是不是系统计算问题呢,还是我不了解纽约的习俗呢?

但是还是可以得到我想要的结果的,运用2个方法:

withearlieroffsetatoverlap(), withlateroffsetatoverlap()

版本2:

    //获取指定时间的 指定时区时间 参照点:默认时区
		public localdatetime getzongtime2(localdatetime time,zoneid dest) {
			objects.requirenonnull(dest);
			return getzongtime2(time, null, dest);
		}
		//版本2 
		public localdatetime getzongtime2(localdatetime time,zoneid src,zoneid dest) {
			 //难点就是如何求偏移量
			//这里使用默认时区,在中国的就是中国,在美国的就是美国,这样估计更合适
			 objects.requirenonnull(dest);
			 zoneddatetime z1=null;
			 if (src==null) {
				 z1 = time.atzone(zoneid.systemdefault());
			 }else{
				 z1 = time.atzone(src);
			 }
//		
			 zoneddatetime z2 = z1.withzonesameinstant(dest);
			 //处理重叠问题
			 long hours = duration.between(z2.withearlieroffsetatoverlap(), z2.withlateroffsetatoverlap()).tohours();
			 z2= z2.plushours(hours);
			 
			 system.out.println(dest.getid()+"对应得标准时区:"+getzonedesc( timezone.gettimezone(dest)));
			 system.out.println("目标时区"+dest+"的时间"+z2.format(datetimeformatter.ofpattern("yyyy-mm-dd hh:mm:ss")));
			 system.out.println("-------------");
			 return time;
		}

测试:ok了

@test 
 public void test4() throws exception { 
   //预计不在夏令时 2016-03-13 01:59:59 
  localdatetime time4= localdatetime.of(2016, 3, 13, 14, 59, 59); 
  getzongtime2(time4,zoneid.of("america/new_york")); 
  
  //预计在夏令时 2016-03-13 03:00:00 
  localdatetime time1= localdatetime.of(2016, 3, 13, 15, 00, 00); 
  getzongtime2(time1,zoneid.of("america/new_york")); 
   
  //预计在夏令时 2016-11-06 02:59:59 
  localdatetime time2= localdatetime.of(2016, 11, 6, 14, 59, 59); 
  getzongtime2(time2,zoneid.of("america/new_york")); 
  //预计不在夏令时2016-11-06 02:00:00 
  localdatetime time3= localdatetime.of(2016, 11, 6, 15, 00, 00); 
  getzongtime2(time3,zoneid.of("america/new_york")); 
    
 } 

结果:

america/new_york对应得标准时区:gmt-5
目标时区america/new_york的时间2016-03-13 01:59:59

-------------

america/new_york对应得标准时区:gmt-5
目标时区america/new_york的时间2016-03-13 03:00:00

-------------

america/new_york对应得标准时区:gmt-5
目标时区america/new_york的时间2016-11-06 02:59:59

-------------

america/new_york对应得标准时区:gmt-5
目标时区america/new_york的时间2016-11-06 02:00:00

-------------

以上这篇基于java时区转换夏令时的问题及解决方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网