How to format a date String into desirable Date format

前端 未结 5 1073
南旧
南旧 2021-01-22 17:11

I was trying to format a string into date.

For this I have written a code:-

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateF         


        
相关标签:
5条回答
  • 2021-01-22 17:33

    This should do it for you, remember to wrap it in a try-catch block just in case.

    DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); 
    try
    {
    Date today = dt.parse("2010-10-22T00:00:00");                       
    System.out.println("Your Date = " + dt.format(today));       
    } catch (ParseException e)    
    {
    //This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
    //Black Magic Goes Here
    } 
    
    0 讨论(0)
  • 2021-01-22 17:33

    The same class you use for output formatting of dates can also be used to parse dates on input.

    • SimpleDateFormat reference

    To use your example, to parse the sample date:

    String dt = "2010-10-22";
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(dateFormatter.parse(dt));
    

    The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.

    0 讨论(0)
  • 2021-01-22 17:54

    If your input is going to be ISO, you could also look at using the Joda Time API, like so:

    LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
    System.out.println("Formatted time: " + localDateTime.toString());
    
    0 讨论(0)
  • 2021-01-22 17:55
    String dt = "2010-10-22";
    
    SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
    ParsePosition ps = new ParsePosition(0)
    Date date = sdfIn.parse(dt, pos)
    
    SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    
    System.out.println(sdfOut.format( date ));
    
    0 讨论(0)
  • 2021-01-22 17:57

    Date Format Example

    Containing the Conversion of String Date object from one format to another

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