在Java中将日期字符串转换为特定日期格式“dd-MM-yyyy”

时间:2012-11-28 14:19:56

标签: java android datetime date-format

我有多个与出生日期的联系人,并且所有联系人都与移动设备同步。现在问题是所有联系人都有不同的生日格式,我想以特定格式显示所有生日日期,如“dd-MM-yyyy”。

例如,一个同步联系人的生日如“1990-02-07”或“1988-06-15T22:00:00.000Z”或“12-02-1990”等... 然后,所有这些日期都应以特定格式“dd-MM-yyyy”显示。

那么我该如何解决这个问题?

任何建议都将受到赞赏。

3 个答案:

答案 0 :(得分:19)

简单地使用SimpleDateFormat类。类似的东西:

Date d = Calendar.getInstance().getTime(); // Current time
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); // Set your date format
String currentData = sdf.format(d); // Get Date String according to date format

您可以在此处查看详细信息和所有支持的格式:

http://developer.android.com/reference/java/text/SimpleDateFormat.html

答案 1 :(得分:3)

我在某种程度上明白你的问题在这里。您可以尝试很长的方式,比如用“ - ”拆分字符串并将其存储在数组中,然后检查数组中的每个字符串,将其解析为int,然后执行条件语句。

假设您提供的格式具有以下格式 “1990-02-07”年 - 月 - 日 “1988-06-15T22:00:00.000Z”年 - 月 - 日时间 “12-02-1990”月 - 日 -

你可以尝试这样的事情。

    public String convert(String s){
        SimpleDateFormat newformat = new SimpleDateFormat("dd-MM-yyyy");
        try{
            if(s.contains("T")){
                String datestring = s.split("T")[0];
                SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
                String reformattedStr = newformat.format(oldformat.parse(datestring));
                return reformattedStr;
            }
            else{
                if(Integer.parseInt(s.split("-")[0])>13){
                    SimpleDateFormat oldformat = new SimpleDateFormat("yyyy-MM-dd");
                    String reformattedStr = newformat.format(oldformat.parse(s));
                    return reformattedStr;
                }
                else{
                    SimpleDateFormat oldformat = new SimpleDateFormat("MM-dd-yyyy");
                    String reformattedStr = newformat.format(oldformat.parse(s));
                    return reformattedStr;
                }

            }
        }
        catch (Exception e){
            return null;
        }
    }

答案 2 :(得分:1)

ISO 8601

  

现在问题是所有联系人都有不同的生日格式

这是真正的问题:以各种格式存储日期时间值。

将日期时间值序列化为文字时,始终使用标准ISO 8601格式。这些格式既合理又实用,避免歧义,易于通过机器解析,也可以通过跨文化的人类可读。

在解析/生成字符串时,java.time类默认使用这些标准格式。

java.time

现代方法使用 java.time 类来取代麻烦的旧遗留日期时间类。避免遗留DateCalendarSimpleDateFormat和相关类。

  

例如,一个同步联系人的生日就像" 1990-02-07"或" 1988-06-15T22:00:00.000Z"或" 12-02-1990"等...

由于含糊不清,解析任何可想到的日期时间格式是不可能的。例如,01-02-1990代表1月2日或2月1日吗?

如果您愿意,可以猜测,但这可能是不明智的,具体取决于准确性对您的业务问题的重要性。

使用DateTimeFormatter定义一堆格式化模式。试试每个。当抛出DateTimeParseException时,继续前进到下一个模式,直到有效。

您可以使用string length来帮助指导猜测。

List < DateTimeFormatter > dateFormatters = new ArrayList <>( 2 );
dateFormatters.add( DateTimeFormatter.ofPattern( "uuuu-MM-dd" ) );  // BEWARE of ambiguity in these formatters regarding month-versus-day.
dateFormatters.add( DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) );

String input = "1990-02-07";
// String input = "12-02-1990" ;

if ( null == input )
{
    throw new IllegalArgumentException( "Passed null argument where a date-time string is expected. Message # c7a4fe0e-9500-45d5-a041-74d457381008." );
} else if ( input.length() <= 10 )
{
    LocalDate ld = null;
    for ( DateTimeFormatter f : dateFormatters )
    {
        try
        {
            ld = LocalDate.parse( input , f );
            System.out.println( ld );
        } catch ( Exception e )
        {
            // No code here.
            // We purposely ignore this exception, moving on to try the next formatter in our list.
        }
    }
} else if ( ( input.length() > 10 ) && input.substring( input.length() - 1 ).equalsIgnoreCase( "Z" ) ) // If over 10 in length AND ends in a Z.
{
    Instant ld = null;
    try
    {
        ld = Instant.parse( input );  // Uses `DateTimeFormatter.ISO_INSTANT` formatter.
    } catch ( Exception e )
    {
        throw new IllegalArgumentException( "Unable to parse date-time string argument. Message # 0d10425f-42f3-4e58-9baa-84ff949e9574." );
    }
} else if ( input.length() > 10 )
{
    // TODO: Define another list of formatters to try here.
} else if ( input.length() == 0 )
{
    throw new IllegalArgumentException( "Passed empty string where a date-time string is expected. Message # 0ffbd9b6-8905-4e28-a732-0f402d4673df." );
} else  // Impossible-to-reach, for defensive programming.
{
    throw new RuntimeException( "ERROR - Unexpectedly reached IF-ELSE when checking input argument. Message # 6228d9e0-047a-4b83-8916-bc526e0fd22d." );
}
System.out.println("Done running.");
  

1990年2月7日

     

完成跑步。

关于 java.time

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

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

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

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

从哪里获取java.time类?

ThreeTen-Extra项目使用其他类扩展java.time。该项目是未来可能添加到java.time的试验场。您可以在此处找到一些有用的课程,例如IntervalYearWeekYearQuartermore