【问题标题】:how to convert milliseconds to date format in android?如何在android中将毫秒转换为日期格式?
【发布时间】:2011-12-18 17:13:25
【问题描述】:

我有几毫秒。 我需要将其转换为

的日期格式

示例:

23/10/2011

如何实现?

【问题讨论】:

    标签: java android android-date date


    【解决方案1】:

    试试这个示例代码:-

    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    
    
    public class Test {
    
    /**
     * Main Method
     */
    public static void main(String[] args) {
        System.out.println(getDate(82233213123L, "dd/MM/yyyy hh:mm:ss.SSS"));
    }
    
    
    /**
     * Return date in specified format.
     * @param milliSeconds Date in milliseconds
     * @param dateFormat Date format 
     * @return String representing date in specified format
     */
    public static String getDate(long milliSeconds, String dateFormat)
    {
        // Create a DateFormatter object for displaying date in specified format.
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
    
        // Create a calendar object that will convert the date and time value in milliseconds to date. 
         Calendar calendar = Calendar.getInstance();
         calendar.setTimeInMillis(milliSeconds);
         return formatter.format(calendar.getTime());
    }
    }
    

    【讨论】:

    • 它适用于超过 10 位数的长值,但不适用于 6 向下。小时的默认值为 4.. ???
    • 你应该使用 new SimpleDateFormat(dateFormat,Locale.US(or your locale)) 而不是 new SimpleDateFormat(dateFormat),因为它会由于更改默认android语言而导致崩溃
    • 仅供参考,java.util.Datejava.util.Calendarjava.text.SimpleDateFormat 等麻烦的旧日期时间类现在已被 java.time 类所取代。在ThreeTen-Backport 项目中,许多java.time 功能被反向移植到Java 6 和Java 7。在ThreeTenABP 项目中进一步适用于早期的Android。见How to use ThreeTenABP…
    • @Uttam 这行得通,谢谢!,但我有一个问题。我们是否应该以这种“/Date(1224043200000)/”格式接收时间和日期?我读过它是微软的旧 json 格式,不应该在新的开发中使用。
    【解决方案2】:

    毫秒 值转换为 Date 实例并将其传递给选择的格式化程序。

    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    String dateString = formatter.format(new Date(dateInMillis)));
    

    【讨论】:

      【解决方案3】:
      public static String convertDate(String dateInMilliseconds,String dateFormat) {
          return DateFormat.format(dateFormat, Long.parseLong(dateInMilliseconds)).toString();
      }
      

      调用这个函数

      convertDate("82233213123","dd/MM/yyyy hh:mm:ss");
      

      【讨论】:

      • 感谢 Mahmood,此解决方案需要 API 级别 1(我的项目已降至 API 15),而其他答案需要 API 级别 24(日期和/或日历库)
      • 如果你是美国人呢?
      • @SteveRogers 这将允许向后兼容developer.android.com/studio/write/…
      【解决方案4】:
      DateFormat.getDateInstance().format(dateInMS);
      

      【讨论】:

        【解决方案5】:

        tl;博士

        Instant.ofEpochMilli( myMillisSinceEpoch )           // Convert count-of-milliseconds-since-epoch into a date-time in UTC (`Instant`).
            .atZone( ZoneId.of( "Africa/Tunis" ) )           // Adjust into the wall-clock time used by the people of a particular region (a time zone). Produces a `ZonedDateTime` object.
            .toLocalDate()                                   // Extract the date-only value (a `LocalDate` object) from the `ZonedDateTime` object, without time-of-day and without time zone.
            .format(                                         // Generate a string to textually represent the date value.
                DateTimeFormatter.ofPattern( "dd/MM/uuuu" )  // Specify a formatting pattern. Tip: Consider using `DateTimeFormatter.ofLocalized…` instead to soft-code the formatting pattern.
            )                                                // Returns a `String` object.
            
        

        java.time

        现代方法使用 java.time 类来取代所有其他 Answers 使用的麻烦的旧的旧日期时间类。

        假设您有一个long 自 1970 年第一刻(UTC,1970-01-01T00:00:00Z)的纪元参考以来的毫秒数……

        Instant instant = Instant.ofEpochMilli( myMillisSinceEpoch ) ;
        

        获取日期需要时区。对于任何给定的时刻,日期在全球范围内因地区而异。

        ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
        ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.
        

        提取仅日期值。

        LocalDate ld = zdt.toLocalDate() ;
        

        使用标准 ISO 8601 格式生成一个表示该值的字符串。

        String output = ld.toString() ;
        

        以自定义格式生成字符串。

        DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
        String output = ld.format( f ) ;
        

        提示:考虑让 java.time 自动为您本地化,而不是硬编码格式模式。使用DateTimeFormatter.ofLocalized… 方法。


        关于java.time

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

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

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

        您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。 Hibernate 5 & JPA 2.2 支持 java.time

        从哪里获取 java.time 类?

        【讨论】:

          【解决方案6】:

          试试这个代码可能会有所帮助,修改它以满足您的需要

          SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
          Date d = format.parse(fileDate);
          

          【讨论】:

            【解决方案7】:

            我终于找到适合我的正常代码

            Long longDate = Long.valueOf(date);
            
            Calendar cal = Calendar.getInstance();
            int offset = cal.getTimeZone().getOffset(cal.getTimeInMillis());
            Date da = new Date(); 
            da = new Date(longDate-(long)offset);
            cal.setTime(da);
            
            String time =cal.getTime().toLocaleString(); 
            //this is full string        
            
            time = DateFormat.getTimeInstance(DateFormat.MEDIUM).format(da);
            //this is only time
            
            time = DateFormat.getDateInstance(DateFormat.MEDIUM).format(da);
            //this is only date
            

            【讨论】:

              【解决方案8】:

              短而有效:

              DateFormat.getDateTimeInstance().format(new Date(myMillisValue))
              

              【讨论】:

                【解决方案9】:
                public class LogicconvertmillistotimeActivity extends Activity {
                    /** Called when the activity is first created. */
                     EditText millisedit;
                        Button   millisbutton;
                        TextView  millistextview;
                        long millislong;
                        String millisstring;
                        int millisec=0,sec=0,min=0,hour=0;
                
                    @Override
                    public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);
                        millisedit=(EditText)findViewById(R.id.editText1);
                        millisbutton=(Button)findViewById(R.id.button1);
                        millistextview=(TextView)findViewById(R.id.textView1);
                        millisbutton.setOnClickListener(new View.OnClickListener() {            
                            @Override
                            public void onClick(View v) {   
                                millisbutton.setClickable(false);
                                millisec=0;
                                sec=0;
                                min=0;
                                hour=0;
                                millisstring=millisedit.getText().toString().trim();
                                millislong= Long.parseLong(millisstring);
                                Calendar cal = Calendar.getInstance();
                                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                                if(millislong>1000){
                                    sec=(int) (millislong/1000);
                                    millisec=(int)millislong%1000;
                                    if(sec>=60){
                                        min=sec/60;
                                        sec=sec%60;
                                    }
                                    if(min>=60){
                                        hour=min/60;
                                        min=min%60;
                                    }
                                }
                                else
                                {
                                    millisec=(int)millislong;
                                }
                                cal.clear();
                                cal.set(Calendar.HOUR_OF_DAY,hour);
                                cal.set(Calendar.MINUTE,min);
                                cal.set(Calendar.SECOND, sec);
                                cal.set(Calendar.MILLISECOND,millisec);
                                String DateFormat = formatter.format(cal.getTime());
                //              DateFormat = "";
                                millistextview.setText(DateFormat);
                
                            }
                        });
                    }
                }
                

                【讨论】:

                • 我们可以通过使用时间单位来做到这一点..但它不能正常工作......使用这个..这会帮助你..它工作正常
                【解决方案10】:

                在 Android (Java / Kotlin) 中将 epoch 格式转换为 SimpleDateFormat

                输入:1613316655000

                输出:2021-02-14T15:30:55.726Z

                在 Java 中

                long milliseconds = 1613316655000L;
                Date date = new Date(milliseconds);
                String mobileDateTime = Utils.getFormatTimeWithTZ(date);
                

                //以String形式返回SimpleDateFormat的方法

                public static String getFormatTimeWithTZ(Date currentTime) {
                    SimpleDateFormat timeZoneDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
                    return timeZoneString = timeZoneDate.format(currentTime);
                }
                

                在科特林中

                var milliseconds = 1613316655000L
                var date = Date(milliseconds)
                var mobileDateTime = Utils.getFormatTimeWithTZ(date)
                

                //以String形式返回SimpleDateFormat的方法

                fun getFormatTimeWithTZ(currentTime:Date):String {
                  val timeZoneDate = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
                  return timeZoneString = timeZoneDate.format(currentTime)
                }
                

                【讨论】:

                • 顺便考虑扔掉长期过时且臭名昭著的麻烦SimpleDateFormat和朋友。看看您是否可以使用desugaring 或将ThreeTenABP 添加到您的Android 项目中,以便使用现代Java 日期和时间API 的java.time。使用起来感觉好多了。
                【解决方案11】:
                    public static Date getDateFromString(String date) {
                
                    Date dt = null;
                    if (date != null) {
                        for (String sdf : supportedDateFormats) {
                            try {
                                dt = new Date(new SimpleDateFormat(sdf).parse(date).getTime());
                                break;
                            } catch (ParseException pe) {
                                pe.printStackTrace();
                            }
                        }
                    }
                    return dt;
                }
                
                public static Calendar getCalenderFromDate(Date date){
                    Calendar cal =Calendar.getInstance();
                    cal.setTime(date);return cal;
                
                }
                public static Calendar getCalenderFromString(String s_date){
                    Date date = getDateFromString(s_date);
                    Calendar cal = getCalenderFromDate(date);
                    return cal;
                }
                
                public static long getMiliSecondsFromString(String s_date){
                    Date date = getDateFromString(s_date);
                    Calendar cal = getCalenderFromDate(date);
                    return cal.getTimeInMillis();
                }
                

                【讨论】:

                • 使用这些方法可以将2016-08-18等字符串格式的日期或任何类型的字符串格式转换为DateFormat,也可以将日期转换为毫秒。
                【解决方案12】:
                public static String toDateStr(long milliseconds, String format)
                {
                    Date date = new Date(milliseconds);
                    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.US);
                    return formatter.format(date);
                }
                

                【讨论】:

                  【解决方案13】:

                  我一直在寻找一种有效的方法来做到这一点,我发现最好的方法是:

                  DateFormat.getDateInstance(DateFormat.SHORT).format(new Date(millis));
                  

                  优点:

                  1. 已本地化
                  2. 从 API 1 开始使用 Android
                  3. 很简单

                  缺点:

                  1. 有限的格式选项。仅供参考:SHORT 只是 2 位数的年份。
                  2. 你每次都烧一个 Date 对象。我查看了其他选项的来源,与它们的开销相比,这相当小。

                  您可以缓存 java.text.DateFormat 对象,但它不是线程安全的。如果你在 UI 线程上使用它就可以了。

                  【讨论】:

                    【解决方案14】:

                    这是使用 Kotlin 最简单的方法

                    private const val DATE_FORMAT = "dd/MM/yy hh:mm"
                    
                    fun millisToDate(millis: Long) : String {
                        return SimpleDateFormat(DATE_FORMAT, Locale.US).format(Date(millis))
                    }
                    

                    【讨论】:

                    • (1) 请不要教年轻人使用陈旧过时且臭名昭著的SimpleDateFormat类。至少不是第一选择。而且不是没有任何保留。今天我们在java.time, the modern Java date and time API, 和它的DateTimeFormatter 中做得更好。是的,您可以在 Android 上使用它。对于较旧的 Android,请使用脱糖或查看 How to use ThreeTenABP in Android Project
                    • (2) 我不认为您打算使用小写 hh?请在此处检查大写和小写之间的区别。
                    • 现代方式是:return Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern(DATE_FORMAT, Locale.US))。是的,它更长,因为它提供了更多关于正在发生的事情的信息,所以这是一个优势。
                    • @OleV.V.调用需要 API 级别 26
                    • @RupamDas 使用 desugaring 或将 ThreeTenABP 添加到您的 Android 项目中,以便在较旧的 Android 版本(API 级别 26 下)上使用现代 Java 日期和时间 API java.time .
                    【解决方案15】:

                    Kotlin 中的最新解决方案:

                    private fun getDateFromMilliseconds(millis: Long): String {
                        val dateFormat = "MMMMM yyyy"
                        val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
                        val calendar = Calendar.getInstance()
                        
                        calendar.timeInMillis = millis
                        return formatter.format(calendar.time)
                    }
                    

                    我们需要添加 Locale 作为 SimpleDateFormat 的参数或使用 LocalDateLocale.getDefault() 是让 JVM 自动获取当前位置时区的好方法。

                    【讨论】:

                      【解决方案16】:

                      对 Android N 及更高版本使用 SimpleDateFormat。使用早期版本的日历 例如:

                      if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                              fileName = new SimpleDateFormat("yyyy-MM-dd-hh:mm:ss").format(new Date());
                              Log.i("fileName before",fileName);
                          }else{
                              Calendar cal = Calendar.getInstance();
                              cal.add(Calendar.MONTH,1);
                              String zamanl =""+cal.get(Calendar.YEAR)+"-"+cal.get(Calendar.MONTH)+"-"+cal.get(Calendar.DAY_OF_MONTH)+"-"+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+cal.get(Calendar.SECOND);
                      
                              fileName= zamanl;
                              Log.i("fileName after",fileName);
                          }
                      

                      输出:
                      之前的文件名:2019-04-12-07:14:47 // 使用 SimpleDateFormat
                      之后的文件名:2019-4-12-7:13:12        // 使用日历

                      【讨论】:

                        【解决方案17】:
                        fun convertLongToTimeWithLocale(){
                            val dateAsMilliSecond: Long = 1602709200000
                            val date = Date(dateAsMilliSecond)
                            val language = "en"
                            val formattedDateAsDigitMonth = SimpleDateFormat("dd/MM/yyyy", Locale(language))
                            val formattedDateAsShortMonth = SimpleDateFormat("dd MMM yyyy", Locale(language))
                            val formattedDateAsLongMonth = SimpleDateFormat("dd MMMM yyyy", Locale(language))
                            Log.d("month as digit", formattedDateAsDigitMonth.format(date))
                            Log.d("month as short", formattedDateAsShortMonth.format(date))
                            Log.d("month as long", formattedDateAsLongMonth.format(date))
                        }
                        

                        输出:

                        month as digit: 15/10/2020
                        month as short: 15 Oct 2020 
                        month as long : 15 October 2020
                        

                        您可以根据需要更改定义为“语言”的值。这是所有语言代码: Java language codes

                        【讨论】:

                        • 考虑扔掉早已过时且臭名昭著的麻烦SimpleDateFormat和朋友。看看您是否可以使用 desugaring 或将 ThreeTenABP 添加到您的 Android 项目中,以便使用现代 Java 日期和时间 API java.time。使用起来感觉好多了。
                        猜你喜欢
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 1970-01-01
                        • 2019-10-21
                        • 2016-02-25
                        • 1970-01-01
                        • 2023-04-06
                        相关资源
                        最近更新 更多