String to Date in Java

后端 未结 4 1667
暖寄归人
暖寄归人 2020-12-12 03:04

HI,

I am converting String to Date format. But it returns wrong dates. for example,

String startDate = \"08-05-2010\"; //  (MM/dd/yyyy)
相关标签:
4条回答
  • 2020-12-12 03:23

    If you want to convert a date string of one format to another format, you can use format() and parse() methods of SimpleDateFormat class

    First you need to parse the string to a date object using parse() method setting the source pattern and then format the date object using format() method setting the target pattern:

    SimpleDateFormat sourceFormat = new SimpleDateFormat("MM-dd-yyyy");
    Date sourceFormatDate = sourceFormat.parse("08-05-2010");
    SimpleDateFormat destFormat = new SimpleDateFormat("dd-MMM-yy");
    String destFormatDateString = destFormat.format(sourceFormatDate);
    System.out.println(destFormatDateString); // 05-Aug-10
    
    0 讨论(0)
  • 2020-12-12 03:26

    The format dd-MMM-yy you use to parse the string is wrong; the format should be dd-MM-yyyy.

    String startDate = "08-05-2010";
    DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
    Date date = dateFormat.parse((startDate));
    

    Note that Date objects themselves do not have a format: a Date objects just represents a date and time value, just like an int is just a number, and doesn't have any inherent formatting information. If you want to display the Date in a certain format, you'll have to use a DateFormat object again to format it:

    DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yy");
    System.out.println(dateFormat.format(date));
    // output: 08-May-10
    
    0 讨论(0)
  • 2020-12-12 03:34

    Unless you've left something out, it looks like you're trying to parse it with the wrong format, i.e. you have an mm-dd-yyyy, and you're trying to parse it with the format dd-MMM-yy. Try a separate date format for what you're parsing from what you're encoding.

    0 讨论(0)
  • 2020-12-12 03:38
    SimpleDateFormat format = new SimpleDateFormat(“yyyy-MM-dd”);
    String strDate = “2007-12-25″;
    Date date = null;
    try {
    
       date = format.parse(strDate);
    
    } catch (ParseException ex) {
    
       ex.printStackTrace();
    
    }
    
    0 讨论(0)
提交回复
热议问题