Android SimpleDateFormat, how to use it?

后端 未结 8 1052
清歌不尽
清歌不尽 2020-11-29 01:54

I am trying to use the Android SimpleDateFormat like this:

String _Date = \"2010-09-29 08:45:22\"
SimpleDateFormat fmt = new SimpleDateFormat(\"         


        
8条回答
  •  被撕碎了的回忆
    2020-11-29 02:24

    I assume you would like to reverse the date format?

    SimpleDateFormat can be used for parsing and formatting. You just need two formats, one that parses the string and the other that returns the desired print out:

    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    Date date = fmt.parse(dateString);
    
    SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
    return fmtOut.format(date);
    

    Since Java 8:

    DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd").withZone(ZoneOffset.UTC);
    TemporalAccessor date = fmt.parse(dateString);
    Instant time = Instant.from(date);
    
    DateTimeFormatter fmtOut = DateTimeFormatter.ofPattern("dd-MM-yyyy").withZone(ZoneOffset.UTC);
    return fmtOut.format(time);
    

提交回复
热议问题