Ergosphere
Ergosphere

Reputation: 67

Java SimpleDateFormat parse returning the wrong day

I'm trying to parse a string in the format of "Monday, May 15 at 1:00 PM" into a datetime so that i can enter it into a database. However the parse isnt returning the right day when i'm testing this out. Does anyone have any ideas what's happening?

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class App 
{
    public static void main( String[] args ) throws ParseException
    {

        String inDateTime = "Monday, May 15 at 1:00 PM";

        Date date = new SimpleDateFormat("EEE, MMM dd 'at' hh:mm aa").parse(inDateTime);

        String outDateTime = new SimpleDateFormat("EEEEEE MMMMMM dd hh:mm aa").format( date );

        System.out.println(outDateTime);

    }
}

And the output from netbeans

[exec:exec]
Friday May 15 01:00 PM

Any ideas why Monday is turning into Friday?

Upvotes: 2

Views: 2854

Answers (2)

Reimeus
Reimeus

Reputation: 159784

You're not setting the year so SimpleDateFormat is using the one from the epoch. May 15 1970 occurred on a Friday.

The day input field is ignored if month and date fields are present so this field can be omitted.

You will need to specify a year where May 15 occurred on a Monday.

Upvotes: 3

Suresh Atta
Suresh Atta

Reputation: 121998

your code is equvalent to

String inDateTime = "1970 Monday, May 15 at 1:00 PM";

    Date date = new SimpleDateFormat("yyyy EEE, MMM dd 'at' hh:mm aa")
                 .parse(inDateTime);

String outDateTime = new SimpleDateFormat("EEEEEE MMMMMM dd hh:mm aa")
                 .format( date );

    System.out.println(outDateTime); //prints Friday May 15 01:00 PM

So please add year

Upvotes: 0

Related Questions