由于项目原因,本人在做测试的时候发时间都是UTC时间,因此找了找解决方案,发现都是非常复杂,十几行代码实现此功能,其中主要都用在计算时间偏移量。我试了一下在calendar的getinstance方法参数修改并不能直接获取UTC时间,在尝试过之后终于找到一个简单的方法,通知data类直接获取时间戳,然后设置时间戳来达到转换时区的方法。分享代码,供大家参考。
本方法只适用于采用北京时间为标准时间的地区。
/**
* 获取calendar类对象,默认UTC时间
*
* @return
*/
public static Calendar getCalendar() {
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date(getDate().getTime() - 8 * 3600 * 1000));
return calendar;
}
在发一下几个关联的封装方法:
/**
* 获取当前星期数(按年)
*
* @return
*/
public static int getWeeksNum() {
return getCalendar().get(Calendar.WEEK_OF_YEAR);
}
/**
* 获取月份
*
* @return
*/
public static int getMonthNum() {
return getCalendar().get(Calendar.MONTH) + 1;
}
/**
* 获取当前是当月的第几天
*
* @return
*/
public static int getDayNum() {
return getCalendar().get(Calendar.DAY_OF_MONTH);
}
/**
* 获取年份
*
* @return
*/
public static int getYearNum() {
return getCalendar().get(Calendar.YEAR);
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有