简体   繁体   English

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

[英]Java convert UTC timestamp to local DateTime

I know there are dozens of answered posts about converting UTC Time/Date To/From local time already but non helped me to figure out what my problem is. 我知道有很多关于将UTC时间/日期转换为当地时间的回复帖子,但没有帮助我弄清楚我的问题是什么。 My question is: By having UTC timestamp, how can i get local DateTime? 我的问题是:通过UTC时间戳,我怎样才能获得本地DateTime? This is what I have right now but this just convert the timestamp to DateTime format. 这就是我现在所拥有的,但这只是将时间戳转换为DateTime格式。

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

Edited: I'm saving the UTC timestamp on the cloud so every device (Android/iOS) can query and convert to it's time zone. 编辑:我在云上保存UTC时间戳,以便每个设备(Android / iOS)都可以查询并转换为它的时区。

Try this is working with me 试试这个和我一起工作

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 "";
    }

You can try this 你可以试试这个

 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

U can use Joda time to convert local to UTC and vice-versa eg Local to UTC 你可以使用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();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM