【问题标题】:How to convert unix time format to day format month date yeear and time format in java如何在java中将unix时间格式转换为日格式月日年和时间格式
【发布时间】:2018-03-27 12:47:35
【问题描述】:

我的时间格式来了 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");

2108-03-27T17:18:16.985+0530

输入日期我要转换成其他时间格式

Mar 27,2018 5:18 pm

预期输出可以任何请建议我如何将给定时间转换为java 中的其他时间格式。

【问题讨论】:

标签: java simpledateformat


【解决方案1】:
SimpleDateFormat sdf = new SimpleDateFormat("MMM d,yyyy h:mm a");
System.out.println(sdf.format(date));

【讨论】:

    【解决方案2】:

    如果您有 Java 8,请使用 java.time API:

    DateTimeFormatter parser = new DateTimeFormatterBuilder()
                    .append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                    .appendPattern("XX")
                    .toFormatter();
    OffsetDateTime odt = OffsetDateTime.parse("2108-03-27T17:18:16.985+0530", parser);
    
    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MMM dd,yyyy h:mm a", Locale.ENGLISH);
    String formattedDate = fmt.format(odt); // Mar 27,2108 5:18 PM
    

    SimpleDateFormatlots of problems,其中许多都通过 java.time API 解决,您应该更喜欢使用这些。

    对于旧版本的 Java,有一个 nice backport,具有相同的类和功能。

    【讨论】:

      【解决方案3】:
          SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm a");
          System.out.println(sdf.format(new Date()));
      

      //2018 年 3 月 27 日下午 6:28

      更多 What are the date formats available in SimpleDateFormat class?

      【讨论】:

      • 我的输入是这种格式的 2108-03-27T17:18:16.985+0530 我将如何将其转换为日期格式@Roushan45
      【解决方案4】:

      您可以将类型任意转换为任意日期格式。

      您只需要将字符串格式传递给SimpleDateFormate

      将此方法用作static,并通过传递inputDate从任何地方调用它

      简化日期转换方法:

      public static String getFormattedDate(String inputDate)
      {
          String outputFormattedDate = "";
          try
          {
              SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z");
              Date inputFormatDate = inputFormat.parse(inputDate);
      
              SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd,yyyy h:mm a");
              outputFormattedDate = outputFormat.format(inputFormatDate);
          }
          catch (Exception ex)
          {
              outputFormattedDate = inputDate;
              ex.printStackTrace();
          }
      
          return outputFormattedDate;
      }
      

      希望对你有所帮助。

      【讨论】:

        猜你喜欢
        • 2015-04-29
        • 2013-12-29
        • 1970-01-01
        • 2013-09-06
        • 2014-05-04
        • 2021-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多