偏移量用java怎样计算时间,如何设置java.util.Date的偏移量?

I have a Date as a String - 15Sep20162040, which I have to format it into another format with Timezone as 2016-09-15T20:40:00+0400.

What I did to do it as follows:

import java.text.ParseException;

import java.text.SimpleDateFormat;

public class DateFormatExample {

private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(

"yyyy-MM-dd'T'HH:mm:ssZ");

private static SimpleDateFormat dateFormatter = new SimpleDateFormat(

"ddMMMyyyyHHmm");

public static void main(String[] args) throws ParseException {

String date = "15Sep20162040";

String result = offsetDateFormat.format(dateFormatter.parse(date));

System.out.println(result); // 2016-09-15T20:40:00+0400

}

}

Now, I have to modify the output based on timezone difference, for example if difference is +0100, output should resemble as: 2016-09-15T20:40:00+0100 and if difference is -0200, output should resemble as: 2016-09-15T20:40:00-0200.

How can I achieve it?

解决方案

You can use SimpleDateFormat's setTimeZone method as below:

import java.text.ParseException;

import java.text.SimpleDateFormat;

import java.util.TimeZone;

public class DateFormatExample {

private static SimpleDateFormat offsetDateFormat = new SimpleDateFormat(

"yyyy-MM-dd'T'HH:mm:ssZ");

private static SimpleDateFormat dateFormatter = new SimpleDateFormat(

"ddMMMyyyyHHmm");

public static void main(String[] args) throws ParseException {

String date = "15Sep20162040";

String result = offsetDateFormat.format(dateFormatter.parse(date));

System.out.println(result); // 2016-09-15T20:40:00+0400

offsetDateFormat.setTimeZone(TimeZone.getTimeZone("GMT-8:00"));

result = offsetDateFormat.format(dateFormatter.parse(date));

System.out.println(result);

}

}

If you simply want to change the timezone at the end of result, please try the following:

String offset = "GMT-8:00";

String date = "15Sep20162040";

date = date+" "+offset;

SimpleDateFormat dateFormatter2 = new SimpleDateFormat("ddMMMyyyyHHmm Z");

SimpleDateFormat offsetDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

offsetDateFormat2.setTimeZone(TimeZone.getTimeZone(offset));

String result = offsetDateFormat2.format(dateFormatter2.parse(date));

System.out.println(result);

Hope this helps.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值