How to format Joda-Time DateTime to only mm/dd/yyyy?

前端 未结 9 1202
挽巷
挽巷 2020-11-29 15:52

I have a string \"11/15/2013 08:00:00\", I want to format it to \"11/15/2013\", what is the correct DateTimeFormatter pattern?

相关标签:
9条回答
  • 2020-11-29 15:57

    I am adding this here even though the other answers are completely acceptable. JodaTime has parsers pre built in DateTimeFormat:

    dateTime.toString(DateTimeFormat.longDate());
    

    This is most of the options printed out with their format:

    shortDate:         11/3/16
    shortDateTime:     11/3/16 4:25 AM
    mediumDate:        Nov 3, 2016
    mediumDateTime:    Nov 3, 2016 4:25:35 AM
    longDate:          November 3, 2016
    longDateTime:      November 3, 2016 4:25:35 AM MDT
    fullDate:          Thursday, November 3, 2016
    fullDateTime:      Thursday, November 3, 2016 4:25:35 AM Mountain Daylight Time
    
    0 讨论(0)
  • 2020-11-29 16:01

    UPDATED:

    You can: create a constant:

    private static final DateTimeFormatter DATE_FORMATTER_YYYY_MM_DD =
              DateTimeFormat.forPattern("yyyy-MM-dd"); // or whatever pattern that you need.
    

    This DateTimeFormat is importing from: (be careful with that)

    import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter;

    Parse the Date with:

    DateTime.parse(dateTimeScheduled.toString(), DATE_FORMATTER_YYYY_MM_DD);
    

    Before:
    DateTime.parse("201711201515",DateTimeFormat.forPattern("yyyyMMddHHmm")).toString("yyyyMMdd");

    if want datetime:

    DateTime.parse("201711201515", DateTimeFormat.forPattern("yyyyMMddHHmm")).withTimeAtStartOfDay();
    
    0 讨论(0)
  • 2020-11-29 16:03

    I think this will work, if you are using JodaTime:

    String strDateTime = "11/15/2013 08:00:00";
    DateTime dateTime = DateTime.parse(strDateTime);
    DateTimeFormatter fmt = DateTimeFormat.forPattern("MM/dd/YYYY");
    String strDateOnly = fmt.print(dateTime);
    

    I got part of this from here.

    0 讨论(0)
  • 2020-11-29 16:07

    Please try to this one

    public void Method(Datetime time)
    {
        time.toString("yyyy-MM-dd'T'HH:mm:ss"));
    }
    
    0 讨论(0)
  • 2020-11-29 16:09
    DateTime date = DateTime.now().withTimeAtStartOfDay();
    date.toString("HH:mm:ss")
    
    0 讨论(0)
  • 2020-11-29 16:10

    Another way of doing that is:

    String date = dateAndTime.substring(0, dateAndTime.indexOf(" "));
    

    I'm not exactly certain, but I think this might be faster/use less memory than using the .split() method.

    0 讨论(0)
提交回复
热议问题