Java将UTC时间戳转换为本地DateTime

时间:2013-09-09 04:12:54

标签: java android datetime timestamp

我知道有很多关于将UTC时间/日期转换为当地时间的回复帖子,但没有帮助我弄清楚我的问题是什么。 我的问题是: 通过UTC时间戳,我如何获得本地DateTime? 这就是我现在所拥有的,但这只是将时间戳转换为DateTime格式。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getDefault());         
sdf.format(new Date(timestamp * 1000));

已编辑:我正在将云时间戳保存在云上,因此每个设备(Android / iOS)都可以查询并转换为它的时区。

3 个答案:

答案 0 :(得分:15)

试试这个与我合作

public  String getDateCurrentTimeZone(long timestamp) {
        try{
            Calendar calendar = Calendar.getInstance();
            TimeZone tz = TimeZone.getDefault();
            calendar.setTimeInMillis(timestamp * 1000);
            calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date currenTimeZone = (Date) calendar.getTime();
            return sdf.format(currenTimeZone);
        }catch (Exception e) {
        }
        return "";
    }

答案 1 :(得分:0)

你可以试试这个

 String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss a z" ;
 final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
 sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
 String dateTimeString =  sdf.format(new Date());
 System.out.println(dateTimeString);   // current UTC time
 long timeStamp=sdf.parse(dateTimeString).getTime(); //current UTC time in milisec
 Calendar cal = Calendar.getInstance();
 cal.setTime(new Date(timeStamp));
 cal.add(Calendar.HOUR_OF_DAY, 5);
 cal.add(Calendar.MINUTE, 30);
 System.out.println(sdf.format(cal.getTime()));  // time relevant to UTC+5.30

答案 2 :(得分:0)

U可以使用Joda时间将本地转换为UTC,反之亦然 例如,本地到UTC


DateTime dateTimeNew = new DateTime(date.getTime(), DateTimeZone.forID("Asia/Calcutta"));
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    String datetimeString = dateTimeNew.toString("yyyy-MM-dd HH:mm:ss");
    long milis = 0;
    try {
        milis = simpleDateFormat.parse(datetimeString).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }