Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert the date from one format to another date object in another format without using any deprecated classes?

Tags:

java

I'd like to convert a date in date1 format to a date object in date2 format.

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy");     SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyyMMdd");     Calendar cal = Calendar.getInstance();     cal.set(2012, 8, 21);     Date date = cal.getTime();     Date date1 = simpleDateFormat.parse(date);     Date date2 = simpleDateFormat.parse(date1);     println date1     println date2 
like image 402
Phoenix Avatar asked Sep 19 '12 22:09

Phoenix


People also ask

Which function is used to convert date from one format to another?

Using java. The LocalDate class represents a date-only value without time-of-day and without time zone. String input = "January 08, 2017"; Locale l = Locale.US ; DateTimeFormatter f = DateTimeFormatter. ofPattern( "MMMM dd, uuuu" , l ); LocalDate ld = LocalDate. parse( input , f );

How can I change the date format of a date object in Java?

You can just use: Date yourDate = new Date(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd"); String date = DATE_FORMAT. format(yourDate);


1 Answers

Use SimpleDateFormat#format:

DateFormat originalFormat = new SimpleDateFormat("MMMM dd, yyyy", Locale.ENGLISH); DateFormat targetFormat = new SimpleDateFormat("yyyyMMdd"); Date date = originalFormat.parse("August 21, 2012"); String formattedDate = targetFormat.format(date);  // 20120821 

Also note that parse takes a String, not a Date object, which is already parsed.

like image 70
João Silva Avatar answered Oct 11 '22 05:10

João Silva