【问题标题】:convert timestamp into current date in android在android中将时间戳转换为当前日期
【发布时间】:2013-09-26 14:50:46
【问题描述】:

我在显示日期时遇到问题,我得到的时间戳为 1379487711,但据此实际时间是 2013 年 9 月 18 日下午 12:31:51,但它显示的时间为 1970 年 17 月 41 日。如何显示为当前时间。

为了显示时间,我使用了以下方法:

private String getDate(long milliSeconds) {
    // Create a DateFormatter object for displaying date in specified
    // format.
    SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    // Create a calendar object that will convert the date and time value in
    // milliseconds to date.
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis((int) milliSeconds);
    return formatter.format(calendar.getTime());
} 

【问题讨论】:

  • 你确定这是毫秒而不是简单的秒吗?用它来检查你的时间:onlineconversion.com/unix_time.htm
  • 当我检查答案是星期三,2013 年 9 月 18 日 07:01:51 UTC
  • 我使用时间戳很长时间 = System.currentMilliSeconds;
  • 如果你愿意,你可以试试这个,对我来说效果很好。 Firebase Functions

标签: java android date timestamp


【解决方案1】:
private String getDate(long time) {
    Calendar cal = Calendar.getInstance(Locale.ENGLISH);
    cal.setTimeInMillis(time * 1000);
    String date = DateFormat.format("dd-MM-yyyy", cal).toString();
    return date;
}

注意我把时间放在 setTimeInMillis 中,而不是 int,注意我的日期格式是 MM 而不是 mm(mm 是分钟,而不是月,这就是为什么你有一个月份应该是“41”的值)

对于 Kotlin 用户:

fun getDate(timestamp: Long) :String {
   val calendar = Calendar.getInstance(Locale.ENGLISH)
   calendar.timeInMillis = timestamp * 1000L
   val date = DateFormat.format("dd-MM-yyyy",calendar).toString()
   return date
}

不要删除的评论: 试图编辑这篇文章的亲爱的人 - 我认为完全改变答案的内容是违反本网站的行为规则的。 今后请不要这样做。 -LenaBru

【讨论】:

  • 但是 DateFormat.format("dd-MM-yyyy", cal).toString();显示错误,静止年份显示 1970
  • 日期格式的导入是:import android.text.format.DateFormat;
  • 它的工作正常现在乘以时间 * 1000 我得到了当前时间。
  • ("dd-MM-yyyy", cal) 无法被 android 识别。 “无法解析方法”
【解决方案2】:

当前日期和时间:

 private String getDateTime() {
        Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
        Long time = System.currentTimeMillis();
        calendar.setTimeInMillis(time);

       //dd=day, MM=month, yyyy=year, hh=hour, mm=minute, ss=second.

        String date = DateFormat.format("dd-MM-yyyy hh:mm:ss",calendar).toString();
        return date;
    }

注意:如果你的结果总是返回 1970,试试这个方法:

Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calender.setTimeInMillis(time * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", calendar).toString();

【讨论】:

    【解决方案3】:

    使用新的--> JAVA.TIME 用于 Android 应用程序定位 >API26

    保存日期时间戳

     @RequiresApi(api = Build.VERSION_CODES.O)
        public long insertdata(String ITEM, String INFORMATION, Context cons)
        {
            long result=0; 
    
                // Create a new map of values, where column names are the keys
                ContentValues values = new ContentValues();
                
                LocalDateTime INTIMESTAMP  = LocalDateTime.now();
                
                values.put("ITEMCODE", ITEM);
                values.put("INFO", INFORMATION);
                values.put("DATETIMESTAMP", String.valueOf(INTIMESTAMP));
            
                try{
    
                    result=db.insertOrThrow(Tablename,null, values);            
    
                } catch (Exception ex) {
                
                    Log.d("Insert Exception", ex.getMessage());
                    
                }
    
                return  result;
    
        }   
    

    INSERTED DATETIMESTAMP 将采用本地日期时间格式 [ 2020-07-08T16:29:18.647 ],适合显示。

    希望对你有帮助!

    【讨论】:

    • 仅供参考,存在严重缺陷的日期时间类,例如 java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 现在是 legacy,被 Java 8 及更高版本中内置的 java.time 类所取代.建议在 2020 年使用它们是糟糕的建议。
    • 那么,我应该使用 like,LocalDateTime myObj = LocalDateTime.now(); 来实现上述相同,@BasilBourque 吗?
    • 我已经用 java.time (JSR-310) 类 @BasilBourque 更新了这个答案
    • 感谢您和@JodaStephen 巨大的努力!
    【解决方案4】:

    tl;博士

    1970-01-01T00:00:00Z 以来,您有许多整秒,而不是毫秒

    Instant
    .ofEpochSecond( 1_379_487_711L )
    .atZone( 
        ZoneId.of( "Africa/Tunis" ) 
    )
    .toLocalDate()
    .format(
        DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) 
    )
    

    2013-09-18T07:01:51Z

    整秒与毫秒

    如上所述,您将秒数与毫秒数混淆了。

    使用 java.time

    其他答案可能正确但已过时。那里使用的麻烦的旧日期时间类现在是遗留的,被 java.time 类所取代。对于 Android,请参阅下面的最后一个项目符号。

    Instant 类表示UTC 中时间轴上的时刻,分辨率为nanoseconds(最多九 (9) 位小数)。

    Instant instant = Instant.ofEpochSecond( 1_379_487_711L ) ;
    

    instant.toString(): 2013-09-18T07:01:51Z

    应用您想要查看这一刻的时区。

    ZoneId z = ZoneId.of( "America/Montreal" ) ;
    ZonedDateTime zdt = instant.atZone( z ) ;
    

    zdt.toString(): 2013-09-18T03:01:51-04:00[美国/蒙特利尔]

    以您想要的格式生成一个表示该值的字符串。

    DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
    String output = zdt.format( f ) ;
    

    18-09-2013

    看到这个code run live at IdeOne.com


    关于java.time

    java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.DateCalendarSimpleDateFormat

    Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。

    要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310

    从哪里获得 java.time 类?

    ThreeTen-Extra 项目通过附加类扩展了 java.time。该项目是未来可能添加到 java.time 的试验场。您可以在这里找到一些有用的类,例如IntervalYearWeekYearQuartermore

    【讨论】:

      【解决方案5】:

      我从这里得到这个:http://www.java2s.com/Code/Android/Date-Type/CreateDatefromtimestamp.htm

      以上答案都不适合我。

      Calendar c = Calendar.getInstance();
      c.setTimeInMillis(Integer.parseInt(tripBookedTime) * 1000L);
      Date d = c.getTime();
      SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy");
      return sdf.format(d);
      

      顺便说一句:("dd-MM-yyyy", cal) 无法被 Android 识别 - “无法解析方法”。

      【讨论】:

      • 这些糟糕的日期时间类在几年前被现代的 java.time 类所取代。建议在 2019 年使用它们是糟糕的建议。
      • 好吧,它没有任何问题,也没有来自最新 AndroidStudio 3.4.1 的任何警告或符号
      • Android Studio 不知道库的质量,只有人类知道。
      • 好的,关于如何将时间戳从 MySQL 转换为 "MMM dd, yyyy" 格式的字符串有什么建议吗?因为此页面上没有其他答案!!!
      • (A) 您不应该要求数据库中的日期时间只是一个整数(从纪元开始计数)。您应该检索一个日期时间对象,一个java.time.OffsetDateTime 对象。 (B) 如果您确实检索了 UTC 中 1970 年第一时刻的整数计数,那么 my Answer 中给出的 Instant.ofEpochSecond( 1_379_487_711L ).atZone( ZoneId.of( "Africa/Tunis" ) ).format( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ) 对您不起作用呢?看到one-liner run live at IdeOne.com
      【解决方案6】:

      如果你的结果总是返回 1970,试试这个方法:

      Calendar cal = Calendar.getInstance(Locale.ENGLISH);
      cal.setTimeInMillis(timestamp * 1000L);
      String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", cal).toString();
      

      您需要将 TS 值乘以 1000

      使用起来非常简单。

      【讨论】:

      • 我知道这有多简单吗@paras
      • ("dd-MM-yyyy hh:mm:ss", cal) 无法被 android 识别。 “无法解析方法”
      【解决方案7】:

      如果你想显示聊天消息看起来像什么应用程序,那么使用下面的方法。您想要根据您的要求更改的日期格式。

      public String DateFunction(long timestamp, boolean isToday)
      {
          String sDate="";
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
          Calendar c = Calendar.getInstance();
          Date netDate = null;
          try {
              netDate = (new Date(timestamp));
              sdf.format(netDate);
              sDate = sdf.format(netDate);
              String currentDateTimeString = sdf.format(c.getTime());
              c.add(Calendar.DATE, -1);
              String yesterdayDateTimeString =  sdf.format(c.getTime());
              if(currentDateTimeString.equals(sDate) && isToday) {
                  sDate = "Today";
              } else if(yesterdayDateTimeString.equals(sDate) && isToday) {
                  sDate = "Yesterday";
              }
          } catch (Exception e) {
              System.err.println("There's an error in the Date!");
          }
          return sDate;
      }
      

      【讨论】:

      • 仅供参考,这些麻烦的旧类现在是遗留的,被 java.time 类所取代。对于 Android,请参阅 ThreeTen-Backport 和 ThreeTenABP 项目。
      【解决方案8】:
        DateFormat df = new SimpleDateFormat("HH:mm", Locale.US);
        final String time_chat_s = df.format(time_stamp_value);
      

      time_stamp_value 变量类型是long

      使用您的代码,它看起来像这样:

      private String getDate(long time_stamp_server) {
      
          SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
          return formatter.format(time_stamp_server);
      } 
      

      我将“毫秒”更改为 time_stamp_server。考虑将毫秒的名称更改为“c”或更全局的名称。 “c”非常好,因为它与时间和计算有关,比毫秒更全局化。所以,你不一定需要一个日历对象来转换,它应该就这么简单。

      【讨论】:

        【解决方案9】:

        用于将时间戳转换为当前时间

        Calendar calendar = Calendar.getInstance();
        TimeZone tz = TimeZone.getDefault();
        calendar.add(Calendar.MILLISECOND, tz.getOffset(calendar.getTimeInMillis()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        java.util.Date currenTimeZone=new java.util.Date((long)1379487711*1000);
        Toast.makeText(TimeStampChkActivity.this, sdf.format(currenTimeZone), Toast.LENGTH_SHORT).show();
        

        【讨论】:

          【解决方案10】:

          将时间戳转换为当前日期:

          private Date getDate(long time) {    
              Calendar cal = Calendar.getInstance();
                 TimeZone tz = cal.getTimeZone();//get your local time zone.
                 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
                 sdf.setTimeZone(tz);//set time zone.
                 String localTime = sdf.format(new Date(time) * 1000));
                 Date date = new Date();
                 try {
                      date = sdf.parse(localTime);//get local date
                  } catch (ParseException e) {
                      e.printStackTrace();
                  }
                return date;
              }
          

          【讨论】:

          • 很好..我犯了一个愚蠢的错误..我忘了乘法..谢谢你的帮助
          猜你喜欢
          • 1970-01-01
          • 2014-09-25
          • 1970-01-01
          • 1970-01-01
          • 2016-11-26
          • 2014-09-06
          • 2011-08-10
          • 1970-01-01
          • 2020-10-19
          相关资源
          最近更新 更多