【问题标题】:how to convert Date in to Feb 26, 2016 in java [duplicate]如何在java中将日期转换为2016年2月26日[重复]
【发布时间】:2017-11-01 08:50:21
【问题描述】:

我的日期格式为 2016 年 2 月 20 日,我必须将其转换为 2016 年 2 月 26 日,请建议我如何将其转换为这种格式。

【问题讨论】:

  • 你能建议我采用哪种格式
  • 这就是文档的用途
  • 日期不同。 20 日转换为 2 月 26 日。确实是时间旅行!
  • @ResearchDevelopment 你的用户名很讽刺。

标签: java android


【解决方案1】:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

  public static void main(String[] args) throws ParseException {

    String theInDate = "2/20/2016";

    String theInFormat = "MM/dd/yyyy";
    String theOutFormat = "MMM dd, yyyy";

    final SimpleDateFormat theSdfInputFormatter = new SimpleDateFormat(theInFormat);
    final SimpleDateFormat theSdfOutputFormatter = new SimpleDateFormat(theOutFormat);

    final Date theDate = theSdfInputFormatter.parse(theInDate);

    final String theDateText = theSdfOutputFormatter.format(theDate);

    System.out.println(theDateText);

    }
}

您可能还想检查日期解析器上的 setLinient(true) 功能。

以及使用新的日期 API

    String theInDate = "2/20/2016";

    String theInFormat = "M/d/yyyy";
    String theOutFormat = "MMM dd, yyyy";

    final DateTimeFormatter theSdfInputFormatter = DateTimeFormatter.ofPattern( theInFormat );
    final DateTimeFormatter theSdfOutputFormatter = DateTimeFormatter.ofPattern(theOutFormat);

    final LocalDate theDate = LocalDate.from( theSdfInputFormatter.parse( theInDate ) );

    final String theDateText = theSdfOutputFormatter.format(theDate);

    System.out.println(theDateText);

注意线程安全。看看javadoc。 此解决方案适用于 Java。对于 Android,正如所标记的,它应该非常相似。 尽管这是一个重复的答案,但我希望它可以帮助某人快速解决问题并了解它是如何工作的,以便进一步自学。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多