简体   繁体   中英

Change date format

I'm having trouble changing the date format to dd/MMM/yyyy .

Here is my current implementation:

final String OLD_FORMAT = "yyyy-MM-dd";

final String NEW_FORMAT = "yyyy-MMM-dd";

//Start Date
String str4=label.getText();
java.util.Date toDate = null;

//System.out.println(str4);

//End Date
String str5=lblNewLabel_3.getText();
java.util.Date newDateString = null;

SimpleDateFormat format = new SimpleDateFormat(OLD_FORMAT);

try {

    toDate=format.parse(str4);

} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

try {
    newDateString=format.parse(str5);
    format.applyLocalizedPattern(NEW_FORMAT);


} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();

}

output: [Tue May 28 00:00:00 WST 2013]

can someone help me with this, thanks! :D

I add this while statement then the date format sets to default again..

System.out.println("From " + toDate);

System.out.println("To " + newDateString );

Calendar cal2 = Calendar.getInstance();

cal2.setTime(toDate);

System.out.println(toDate);

while (cal2.getTime().before(newDateString)) {
    cal2.add(Calendar.DATE, 1);
    Object datelist=(cal2.getTime());
    List<Object> wordList = Arrays.asList(datelist);  
    System.out.println(wordList);
}

java.util.Date does not have a format. It is simply the number of millisecond since January 1, 1970, 00:00:00 GMT

When you do a System.out.println(new Date()) it is simply providing the Date objects default toString methods output.

You need to use a DateFormat to actually format the Date to a String

public class TestDate01 {

    public static final String OLD_FORMAT = "yyyy-MM-dd";
    public static final String NEW_FORMAT = "yyyy-MMM-dd";

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            String oldValue = "2013-05-29";
            Date date = new SimpleDateFormat(OLD_FORMAT).parse(oldValue);
            String newValue = new SimpleDateFormat(NEW_FORMAT).format(date);
            System.out.println("oldValue = " + oldValue + "; date = " + date + "; newValue = " + newValue);
        } catch (ParseException exp) {
            exp.printStackTrace();
        }
    }
}

Which outputs...

oldValue = 2013-05-29; date = Wed May 29 00:00:00 EST 2013; newValue = 2013-May-29

Extended to meet changed requirements

You're making the same mistake. Date is a container for the number of milliseconds since the epoch, it does not have any format of it's own and instead uses its own format.

try {
    Date toDate = new Date();
    String newDateString = "2013-05-31";

    System.out.println("From " + toDate);
    System.out.println("To " + newDateString);

    Date endDate = new SimpleDateFormat(OLD_FORMAT).parse(newDateString);

    System.out.println("endDate " + endDate);

    Calendar cal2 = Calendar.getInstance();
    cal2.setTime(toDate);
    System.out.println(toDate);

    SimpleDateFormat newFormat = new SimpleDateFormat(NEW_FORMAT);

    while (cal2.getTime().before(endDate)) {
        cal2.add(Calendar.DATE, 1);
        Date date = (cal2.getTime());
        System.out.println(date + "/" + newFormat.format(date));
    }
} catch (Exception exp) {
    exp.printStackTrace();
}

Which outputs...

From Wed May 29 15:56:48 EST 2013
To 2013-05-31
endDate Fri May 31 00:00:00 EST 2013
Wed May 29 15:56:48 EST 2013
Thu May 30 15:56:48 EST 2013/2013-May-30
Fri May 31 15:56:48 EST 2013/2013-May-31

You while does not make sense.

Object datelist=(cal2.getTime());
List<Object> wordList = Arrays.asList(datelist);

cal2.getTime() returns a Date , then you try and create a list from it...maybe I'm missing something though...

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");  
String str4=label.getText();
    Date date=null;
    try {
        date = formatter.parse(str4);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }  
    formatter = new SimpleDateFormat("dd/MMM/yyyy"); 

    System.out.println("Date :" +formatter.format(date));  

Check the below code snippet

 try {
            SimpleDateFormat sdin = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdout = new SimpleDateFormat("yyyy-MMM-dd");
            Date date = sdin.parse("2013-05-31");
            System.out.println(sdout.format(date));
        } catch (ParseException ex) {
            Logger.getLogger(TestDate.class.getName()).log(Level.SEVERE, null, ex);
        }

I wrote a static utility method that you can just drop in and use...and hopefully it is clear enough to demonstrate the proper use of the SimpleDateFormat parse() and format() methods:

  /**
   * Returns a reformatted version of the input date string, where the format 
   * of the input date string is specified by dateStringFormat and the format 
   * of the output date string is specified by outputFormat.  Format strings 
   * use SimpleDateFormat format string conventions.
   *
   * @param dateString input date string
   * @param dateStringFormat format of the input date string (e.g., dd/MM/yyyy)
   * @param outputFormat format of the output date string (e.g., MMM dd, yyyy)
   *
   * @return reformatted date string
   *
   * @throws ParseException if an error occurs while parsing the input date 
   *                        string using the provided format
   *
   * @author Steve
   */
  public static final String reformatDateString(final String dateString,
                                                final String dateStringFormat,
                                                final String outputFormat) 
                                                throws ParseException {

     final SimpleDateFormat dateStringParser = new SimpleDateFormat(dateStringFormat);
     final SimpleDateFormat outputFormatter = new SimpleDateFormat(outputFormat);

     return outputFormatter.format(dateStringParser.parse(dateString));
  }

You call it as follows:

   System.out.println(reformatDateString("2013-5-28", "yyyy-MM-dd", "dd/MMM/yyyy"));

Which, in this example, will output this:

   28/May/2013

The basic idea is that you generally use a SimpleDateFormat instance for one of two things:

  1. To convert a String containing a date with a known format to a java.util.Date instance...using the parse() method, or
  2. To convert a java.util.Date instance to a String of a specified format...using the format() method.

I am doing both in one line in the method that I wrote using the two different SimpleDateFormat instances that I create in that method - one created using the input format (for parsing the original String into a Date instance)...and one created using the output format (for converting the created Date back into a String with the desired format).

If you want to display the date in a certain format, you should be using format function and use String output to display, and not a date object

eg Consider this code:

String pattern = "dd/MM/yyyy";
DateFormat df = new SimpleDateFormat(pattern);
Date d = new Date();
try {
   String outputString = df.format(d);
   System.out.println("outputString :"+outputString);
} catch (ParseException e) {
   e.printStackTrace();
}

parse function is just to parse a string from a particular format to create a Date object but it will not change any of date object display properties.

System.out.println(format.format(toDate))

这将以要求的格式显示日期。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM