【问题标题】:How to format date in android output as : 11/12/2013 4:21 PM如何将 android 输出中的日期格式化为:11/12/2013 4:21 PM
【发布时间】:2014-01-27 13:03:00
【问题描述】:

我在 String 中有一个时间戳,它在 Android 应用程序中返回低于我的值

1398876631

如何将其格式化为以下值

11/12/2013 4:21 PM

【问题讨论】:

  • 你搜索过 SO 吗?
  • 是的,我搜索过,但我找不到输入为字符串且输出为我要查找的格式的答案。

标签: android date format timestamp


【解决方案1】:

请尝试以下功能。在这里你必须传递毫秒和日期格式(如 dd-MM-yyyy HH:mm:ss aa)

public static String getDate(long milliSeconds, String dateFormat)
    {
        // Create a DateFormatter object for displaying date in specified format.
        DateFormat 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());
    }

例子

Log.i("====== Date "," :: "+getDate(1398876631,"dd/MM/yyyy HH:mm aa"))

【讨论】:

    【解决方案2】:

    将您的时间戳转换为日期

    Date d = new Date(Long.parseLong(timestamp) * 1000);
    

    然后使用 SimpleDateFormat,您可以根据需要设置日期格式

    String result = new SimpleDateFormat("dd/MM/yyyy hh:mm").format(d);
    

    【讨论】:

    • 整数溢出:使用 long 表示毫秒时间戳,例如1000L 而不是 1000
    【解决方案3】:

    您的问题答案

     SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy h:mm a");
     String date = df.format(Calendar.getInstance().getTime());
     Log.d("date",date.toString());// Output 01/09/2014 10:59 AM
    

    您可以在哪里使用 DateFormat 模式,例如:

    "yyyy.MM.dd G 'at' HH:mm:ss z" ---- 2001.07.04 AD at 12:08:56 PDT
    "hh 'o''clock' a, zzzz" ----------- 12 o'clock PM, Pacific Daylight Time
    "EEE, d MMM yyyy HH:mm:ss Z"------- Wed, 4 Jul 2001 12:08:56 -0700
     "yyyy-MM-dd'T'HH:mm:ss.SSSZ"------- 2001-07-04T12:08:56.235-0700
     "yyMMddHHmmssZ"-------------------- 010704120856-0700
     "K:mm a, z" ----------------------- 0:08 PM, PDT
     "h:mm a" -------------------------- 12:08 PM
     "EEE, MMM d, ''yy" ---------------- Wed, Jul 4, '01
    

    查看此link 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 2015-06-07
      • 1970-01-01
      • 2011-04-29
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多