错误地将时间戳转换为日期版本

时间:2016-11-22 14:27:45

标签: android

我正在尝试将此时间戳值转换为日期,但它给了我错误的时间。日期是正确的

TimeStamp : 1423821615
True Value : Fri, 13 Feb 2015 10:00:15 GMT
Android Code shows : Fri, 13 Feb 2015 15:30:15 IST

以下是我用来将时间戳转换为日期的代码。

Date dt = new Date((long)timestampInSeconds * 1000);

我也尝试了这段代码但结果相同

public static Date getDateFromTimeStamp(long timestampInMilliseconds) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestampInMilliseconds);
    return cal.getTime();
}

Date dt = getDateFromTimeStamp((long)timestampInSeconds * 1000);

我不知道我做错了什么。请帮忙

现在我解释整个场景。我的客户来自英国,我来自印度(提前5:30)。他明显在英国上午10点创建了约会。但现在我的本地PC上有他的数据库。我的.NET软件显示的时间与SQL服务器的下图相同。但在移动设备方面却没有。 PC和手机都在同一时区。

enter image description here

我使用此代码将日期转换为时间戳,并通过网络服务将此时间戳发送到移动应用

SELECT DATEDIFF(SECOND,{d '1970-01-01'}, Appointments.DateTime) AS AppointmentTimeStamp FROM Appointments

这是我的.NET软件显示的图像 enter image description here

当数据库在英国时区时创建记录是否重要。或者我在某个地方仍然犯了一个错误。

1 个答案:

答案 0 :(得分:0)

我不明白你想要得到什么。 如果您有时间作为EPOCH时间,您将无法获得有关制作此时间戳的时区的信息。因此,您应该知道时区偏移量,并且从此时间戳开始+或减去此秒数。

但我认为使用ISO 8601格式制作时间戳的最佳方法是,您可以轻松转换为您需要的任何时区

例如,此代码将ISO数据转换为本地时间或返回当前时间取决于区域设置时区

private long time2LocalTimeZone (String date){

        //"2016-07-29T23:07:45.120+00"
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());

        try {

            return sdf.parse(date).getTime();

        } catch (ParseException e){

            return (new Date()).getTime();

        }
    }

此代码计算您与GMT时区的偏移量并转换为纪元时间取决于区域设置时区

private long time2LocalTimeZone (long date){
        TimeZone tz = TimeZone.getDefault();
        Date now = new Date();
        int offsetFromUtc = tz.getOffset(now.getTime()) / 1000;
        return date + offsetFromUtc;
    } 
相关问题