【问题标题】:Returing timestamp in milliseconds以毫秒为单位返回时间戳
【发布时间】:2011-08-02 17:54:10
【问题描述】:

我在将日期和时间转换为毫秒时遇到问题。代码中没有错误,但它以毫秒为单位返回错误的日期和时间。

这是我要转换的日期:2011-03-01 17:55:15,它给了我这个数字:-679019461843345152

这是我正在使用的代码:

public long getDate(String s)
{
    //this is returning a timestamp but the wrong ones!!!
    String[] formats = new String[]{
            // "yyyy-MM-dd",
            "yyyy-MM-dd HH:mm:ss"
            // "yyyy-MM-dd HH:mmZ",
            //"yyyy-MM-dd HH:mm:ss.SSSZ",
    };

    SimpleDateFormat sdf = null;
    String st;

    for (String format : formats)
    {
        sdf = new SimpleDateFormat(format, Locale.US);
        //System.err.format("%30s %s\n", format, sdf.format(new Date(0)));

        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        st = new String(sdf.format(new Date(0)));
        System.err.format(format, st);
    }

    // compute nanoseconds from y, m...

    //return that number 
    Calendar c = Calendar.getInstance();
    c.set(sdf.YEAR_FIELD, sdf.MONTH_FIELD, sdf.DATE_FIELD, sdf.HOUR0_FIELD, sdf.MINUTE_FIELD, sdf.SECOND_FIELD);
    return c.getTimeInMillis() * 1000000;
}

【问题讨论】:

    标签: android date time timestamp milliseconds


    【解决方案1】:

    c.set 行没有任何意义:

    c.set(sdf.YEAR_FIELD, sdf.MONTH_FIELD, sdf.DATE_FIELD, sdf.HOUR0_FIELD, sdf.MINUTE_FIELD, sdf.SECOND_FIELD);
    

    这应该会给你一个想法:

           Calendar c = Calendar.getInstance();
           try {
               dt = sdf.parse("2011-03-01 17:55:15"); 
           } catch (ParseException e) {
               System.err.println("There's an error in the Date!");
               return null;
           }   
           Date dt = sdf.parse("2011-03-01 17:55:15");   
           c.setTime(dt);
           System.out.println( c.getTimeInMillis() * 1000000);   
           System.out.println(dt.toString());   
    

    输出:

    1299002115000000000
    Tue Mar 01 12:55:15 EST 2011
    

    顺便说一句,您永远不会访问参数 s。

    【讨论】:

    • 非常感谢,但是当我添加你发送到我的代码的内容时,我遇到了一个小问题,它向我显示了一个错误,它说 Unhandled exception type ParseException for this Date dt = sdf.parse( s)
    • 通常每个解析文本的函数都需要在 try-catch 块中,以处理意外字符串。我将更新答案以向您展示一个示例。
    • 好的,我得到了和你一样的结果,非常感谢你的帮助,但我有最后一个问题,你输入的时间是 17:55:15,你得到的结果是一样的我得到的是 12:55:15....????
    • UTC。与美国东部标准时间 :) 。玩那个。
    猜你喜欢
    • 2012-10-05
    • 2023-03-11
    • 1970-01-01
    • 2015-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-03
    相关资源
    最近更新 更多