javadatesimpledateformat

How can I format a Date in Java as only month, day and hour?


How would I format the date, if I only need it to print the month (MMM), date (DD) and the hour (HH)?

So output would look something like:

Jul 18 9

(that being July 18th 09:00).

I've tried the following

private static void createDate () {

    String startConcat = startMonth + " " + startDate + " " + startTime;
    DateFormat start = new SimpleDateFormat ("MMM DD H");

    try {
       Date date = (Date)start.parse(startConcat);
       System.out.println(date);

    } catch (ParseException e) {
    }
}

Also it doesn't seem to read my month properly too...I am getting this as an output

Sun Jan 18 09:00:00 EST 1970

any help would be deeply appreciated.


Solution

  • You should use the format (javadoc) method.

    private static void createDate () throws Exception {
        String startConcat = startMonth + " " + startDate + " " + startTime;
        DateFormat formatter = new SimpleDateFormat ("MMM DD H");
    
        Date date = (Date) formatter.parse(startConcat);
        System.out.println(formatter.format(date));
    }