Muhammad Imran Tariq
Muhammad Imran Tariq

Reputation: 23352

JAVA Date Conversion

How can I convert

Wed Apr 27 17:53:48 PKT 2011

to

Apr 27, 2011 5:53:48 PM.

Upvotes: 1

Views: 9971

Answers (6)

Yossale
Yossale

Reputation: 14361

SimpleDateFormat sdf = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");

String str = sdf.format(date)

Upvotes: 1

MarcoS
MarcoS

Reputation: 13564

You can do it using a mix of JDK and Joda time:

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

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class SO5804637 {

    public static void main(String[] args) throws ParseException {
        DateFormat df = 
            new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        Date d = df.parse("Wed Apr 27 17:53:48 PKT 2011");
        DateTimeFormatter dtf = 
            DateTimeFormat.forPattern("MMM dd, yyyy hh:mm:ss a");
        DateTime dt = new DateTime(d);
        System.out.println(dt.toString(dtf));
    }

}

Note: I've included the import statements to make it clear what classes I'm using.

Upvotes: 1

laz
laz

Reputation: 28638

new java.text.SimpleDateFormat("MMM d, yyyy h:mm:ss a").format(date);

I noticed your desired output had the hour of day not prefixed by 0 so the format string you need should have only a single 'h'. I'm guessing you want the day of the month to have a similar behavior so the pattern contains only a single 'd' too.

Upvotes: 0

卢声远 Shengyuan Lu
卢声远 Shengyuan Lu

Reputation: 32004

new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a.").format(yourDate);

Upvotes: 5

NickGreen
NickGreen

Reputation: 1752

You can use SimpleDateFormat to convert a string to a date in a defined date presentation. An example of the SimpleDateFormat usage can be found at the following place: http://www.kodejava.org/examples/19.html

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533442

You can use SimpleDateFormat or JodaTime's parser.

However it might be simple enough to write your own String parser as you are just rearranging fields.

Upvotes: 2

Related Questions