由于项目原因,本人在做测试的时候发时间都是UTC时间,因此找了找解决方案,发现都是非常复杂java获取指定时区时间,十几行代码实现此功能java获取指定时区时间 java利用时间戳来获取UTC时间,其中主要都用在计算时间偏移量。我试了一下在的方法参数修改并不能直接获取UTC时间,在尝试过之后终于找到一个简单的方法,通知data类直接获取时间戳java获取指定时区时间,然后设置时间戳来达到转换时区的方法。分享代码,供大家参考。
本方法只适用于采用北京时间为标准时间的地区。
<pre class="cm-s-default" style="color:rgb(89,89,89);margin:0px;padding:0px;background:rgba(0,0,0,0) none repeat scroll 0% 0%;">/* 2 获取calendar类对象,默认UTC时间 3 4 @return 5 / 6 public static Calendar getCalendar() { 7 Calendar calendar = Calendar.getInstance(); 8 calendar.setTime(new Date(getDate().getTime() - 8 3600 * 1000)); 9 return calendar; 10 }</pre>
在发一下几个关联的封装方法:
<pre class="cm-s-default" style="color:rgb(89,89,89);margin:0px;padding:0px;background:rgba(0,0,0,0) none repeat scroll 0% 0%;">/ 2 获取当前星期数(按年) 3 4 @return 5 / 6 public static int getWeeksNum() { 7 return getCalendar().get(Calendar.WEEK_OF_YEAR); 8 } 9 10 / 11 获取月份 12 13 @return 14 / 15 public static int getMonthNum() { 16 return getCalendar().get(Calendar.MONTH) + 1; 17 } 18 19 / 20 获取当前是当月的第几天 21 22 @return 23 / 24 public static int getDayNum() { 25 return getCalendar().get(Calendar.DAY_OF_MONTH); 26 } 27 28 / 29 获取年份 30 31 @return 32 / 33 public static int getYearNum() { 34 return getCalendar().get(Calendar.YEAR); 35 }</pre>