How to convert String to Date in java whatever system format is

This question already has an answer here:

  • Parse any date in Java 3 answers

  • You're trying to convert a String in EEEE, MMMM dd, yyyy format with the format of dd/MM/yyyy ...

    Start by using the correct format for the String you trying to convert, the use what ever format you want to convert it back...

    SimpleDateFormat from = new SimpleDateFormat("EEEE, MMMM dd, yyyy");
    SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
    
    String value = to.format(from.parse(dateString));
    

    Now you could use something like DateUtils.parseDate(String, String[]) which allows to supply a number of different formats, but is still limited to what you might know.

    A better solution would be to store the Date value directly within the database.


  • You are passing wrong parameter to SimpleDateFormater
  • Use SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM dd, yyyy") instead of SimpleDateFormat to = new SimpleDateFormat("dd/MM/yyyy");
  • It resolve your Unparseable date issue.

  • Try to use something like this:

    public static String dateToString(String date){
        if(date.equals("")) return "";
        if(date == null || date.length() == 0){
            return "";
        }
        SimpleDateFormat formatIn = new SimpleDateFormat("dd/MM/yyyy");
        SimpleDateFormat formatOut = new SimpleDateFormat("yyyy-dd-MM");
    
        try {
            Date l_date =  formatIn.parse(date);
            String result = formatOut.format(l_date);
            return result;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }
    }
    

    but if you want to put some data into database you may also use instead String java.sql.Date

    something like this:

    SimpleDateFormat format = new SimpleDateFormat();
    
    Connection conn = ...
    PreparedStatement ps = conn.prepareStatement("...");
    
    long lDate = format.parse(sDate).getTime();
    java.sql.Date dDate = new java.sql.Date(lDate);
    ps.setDate(1, dDate);
    
    链接地址: http://www.djcxy.com/p/84546.html

    上一篇: Java在Mac OS X上安装在哪里?

    下一篇: 如何在Java中将字符串转换为日期,无论系统格式是什么