【问题标题】:Format date string to remove time in JAVA格式化日期字符串以删除 JAVA 中的时间
【发布时间】:2013-09-21 12:18:16
【问题描述】:

例如,字符串值为:

15/08/2013 15:30 GMT+10:00 

我想在 Java 中将上面的字符串格式化为15/08/2013(去掉时间部分,只保留日期)。

我怎样才能做到这种格式?

【问题讨论】:

  • 使用 SimpleDateFormat 代码 - DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm z");

标签: java string date


【解决方案1】:

去掉时间部分,只保留日期

String dateString= "15/08/2013 15:30 GMT+10:00";
String result  = dateString.split(" ")[0];

给你15/08/2013

我猜不需要格式化。

【讨论】:

  • 因为我只有日期字符串并且没有日期变量。也只是希望它格式化以仅保留日期部分。所以,它会工作。谢谢。
  • @Dhaval Me 也只使用了日期字符串,不是日期对象。仔细看看。
  • 简单,先生@SureshAtta
【解决方案2】:

2018

现在是 2018 年,我们在 Java 8+(和 ThreeTen Backport)中拥有日期/时间 API,您可以执行类似...

String text = "15/08/2013 15:30 GMT+10:00";
LocalDateTime ldt = LocalDateTime.parse(text, DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm z", Locale.ENGLISH));
System.out.println(ldt);

// In case you just want to do some "date" manipulation, without the time component
LocalDate ld = ldt.toLocalDate();
// Will produce "2013-08-15"
//String format = ldt.format(DateTimeFormatter.ISO_LOCAL_DATE);
String format = ldt.format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(format);

原答案

一种方法是将String 日期解析为Date 对象,然后根据您的要求简单地格式化

String text = "15/08/2013 15:30 GMT+10:00";
SimpleDateFormat inFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm z");
Date date = inFormat.parse(text);
System.out.println(date);

SimpleDateFormat outFormat = new SimpleDateFormat("dd/MM/yyyy");
String formatted = outFormat.format(date);
System.out.println(formatted);

如果您需要将日期/时间信息保存在Date 中以用于其他事情,这样做的好处是;)

更多详情请见SimpleDateFormat

【讨论】:

    【解决方案3】:

    如果这只不过是你有一个包含15/08/2013 15:30 GMT+10:00 的字符串,而你只想要日期部分,即字符串的前 10 个字符,我只取前 10 个字符;无需将其解析并格式化为日期:

    String input = "15/08/2013 15:30 GMT+10:00";
    String result = input.substring(0, 10);
    

    【讨论】:

      【解决方案4】:

      【讨论】:

        【解决方案5】:
        DateFormat formatter = new SimpleDateFormat(format);
        Date date = (Date) formatter.parse(dateStr);
        

        【讨论】:

          【解决方案6】:

          查看 DateFormat 类, http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

          您应该能够使用解析器解析日期,然后以另一种模式写出您想要的格式

          即入站的新 SimpleDateFormat("dd/MM/yyyy hh:mm z")

          new SimpleDateFormat("dd/MM/yyyy") 为您更新的格式

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2023-03-14
            • 1970-01-01
            • 1970-01-01
            • 2017-06-14
            • 1970-01-01
            • 2013-09-13
            • 2012-09-07
            相关资源
            最近更新 更多