Java 在android中将时间戳转换为当前日期

Java 在android中将时间戳转换为当前日期,java,android,date,timestamp,Java,Android,Date,Timestamp,我在显示日期时遇到问题,我得到的时间戳是1379487711,但根据这一点,实际时间是2013年9月18日12:31:51,但它显示的时间是17-41-1970。如何将其显示为当前时间 对于显示时间,我使用了以下方法: private String getDate(long milliSeconds) { // Create a DateFormatter object for displaying date in specified // format. SimpleD

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

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

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());
} 
请注意,我将时间设置为setTimeInMillis,长度与int相同,而不是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
}
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calender.setTimeInMillis(time * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", calendar).toString();
不删除的注释: 亲爱的人谁试图编辑这篇文章-完全改变了答案的内容,我相信,违反了本网站的行为规则。
今后请不要这样做-LenaBru

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

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

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

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();
时间戳值变量类型为long

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

private String getDate(long time_stamp_server) {

    SimpleDateFormat formatter = new SimpleDateFormat("dd-mm-yyyy");
    return formatter.format(time_stamp_server);
} 

我将“毫秒”更改为时间戳服务器。考虑将毫秒名改为“C”或更为全局。“c”真的很好,因为它与时间和计算的关系比毫秒更为全局。因此,您不一定需要日历对象来转换,它应该如此简单

如果你想让聊天信息看起来像什么样的应用程序,那么使用下面的方法。您希望根据需要更改的日期格式

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;
}
tl;博士 自
1970-01-01T00:00:00Z
以来,您拥有的是整秒数,而不是毫秒数

2013-09-18T07:01:51Z

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

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

该类表示时间线上的一个时刻,分辨率为(小数点的九(9)位)

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

看这个


关于java.time 该框架内置于Java8及更高版本中。这些类取代了麻烦的旧日期时间类,例如,&

该项目现已启动,建议迁移到类

要了解更多信息,请参阅。并搜索堆栈溢出以获得许多示例和解释。规格是

从哪里获得java.time类

  • ,及以后
    • 内置的
    • 标准JavaAPI的一部分,带有捆绑实现
    • Java9添加了一些次要功能和修复
    • 大部分java.time功能都在中向后移植到Java6和Java7
    • 该项目专门为Android采用了ThreeTen Backport(如上所述)

该项目使用其他类扩展了java.time。这个项目是java.time将来可能添加的一个试验场。您可以在此处找到一些有用的类,如、、和。

如果结果总是返回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

它使用起来非常简单。

我从这里得到了这个:

以上所有答案对我都不起作用

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 FOR ANDROID应用程序TARGETING>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;

    }   
插入的日期时间戳将采用适合显示的本地日期时间格式[2020-07-08T16:29:18.647]

希望有帮助

当前日期和时间:

 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,请尝试以下方法:

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
}
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calender.setTimeInMillis(time * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", calendar).toString();

你确定这是以毫秒为单位,而不是以简单秒为单位吗?使用此项检查您的时间:当我检查答案为Wed时,2013年9月18日07:01:51 UTCI am使用时间戳作为long time=System.currentmicles;如果你愿意的话,你可以试试这个,对我来说,它非常好用。但是DateFormat.format(“dd-MM-yyyy”,cal).toString();显示错误并显示年份1970 DateFormat的导入为:import android.text.format.DateFormat;它现在工作正常乘以时间*1000我得到了当前时间。
(“dd-MM-yyyy”,cal)
不被android识别。“无法解析方法”非常好。。我犯了一个愚蠢的错误。。我忘了乘法。。感谢您的帮助,这些麻烦的旧类现在是遗留类,被java.time类取代。对于Android,请参阅Three-Ten Backport和Three-TeNABP项目。我想知道@paras
(“dd-MM-yyy-hh:MM:ss”,cal)是多么容易。
是Android无法识别的。“无法解析方法”这些糟糕的日期时间类在几年前被现代的java.time类所取代。建议在2019年使用它们是一个糟糕的建议。好吧,它没有任何问题,也没有最新AndroidStudio 3.4.1中的任何警告或注释。Android Studio不知道库的质量,只有人类知道。好的,关于如何将时间戳从MySQL转换为“MMM dd,yyyy”格式的字符串,有什么建议吗???因为本页没有其他答案!!!(A) 您不应该要求数据库中的日期时间仅仅是一个整数(来自历元的计数)。您应该检索一个日期时间对象,一个
java.time.OffsetDateTime
对象。(B) 如果您确实在UTC中从1970年第一个时刻的历元中检索到整数计数,那么
瞬变秒(1_379_487_711L).atZone(ZoneId.of(“非洲/突尼斯”)).format(Dat)呢
 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;
    }
Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
calender.setTimeInMillis(time * 1000L);
String date = DateFormat.format("dd-MM-yyyy hh:mm:ss", calendar).toString();