Skip to content
Advertisement

How to convert mm/dd/yy string to “Monday 7th Jan”

I have a database file with mm/dd/yy values for events, and I want to display the date as something similar to “Day(word), day(number), month(word)”.

01/07/19 into
Monday 4th Jan or Monday 4 Jan or something similar.

Advertisement

Answer

You can use SimpleDateFormat to convert the string to date and then convert back to String like this :

     DateFormat format1 = new SimpleDateFormat("MM-dd-yyyy");
     Date date = format1.parse("01-01-2019");
     DateFormat format2 = new SimpleDateFormat("MMMMM dd, yyyy");
     String dateString = format2.format(date);
     System.out.println(dateString); //<- prints January 01, 2019

How to use the SimpleDateFormat?
Java provides a class called a SimpleDateFormat that allows you to format and parse dates in the as per your requirements.

You can use the above characters to specify the format – For example:

1) Date format required: 2019.01.01 20:20:45 PST

The appropriate date format specified will be- yyyy.MM.dd HH:mm:ss zzz

2) Date format required:09:30:00 AM 01-Jan-2019

The appropriate date format specified will be-hh:mm:ss a dd-MMM-yyyy

Tip: Be careful with the letter capitalization. If you mistake M with m, you will undesired results!

Let’s learn this with a code example.

import java.text.SimpleDateFormat;
import java.util.Date;
public class TestDates_Format {
 public static void main(String args[]) {
  Date objDate = new Date(); // Current System Date and time is assigned to objDate
  System.out.println(objDate);
  String strDateFormat = "hh:mm:ss a dd-MMM-yyyy"; //Date format is Specified
  SimpleDateFormat objSDF = new SimpleDateFormat(strDateFormat); //Date format string is passed as an argument to the Date format object
  System.out.println(objSDF.format(objDate)); //Date formatting is applied to the current date
 }
}

Output :

Sat Mar 02 16:37:59 UTC 2019
04:37:59 PM 02-Mar-2019

Have a nice day !

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement