문제

How can I convert

Wed Apr 27 17:53:48 PKT 2011

to

Apr 27, 2011 5:53:48 PM.
도움이 되었습니까?

해결책

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

다른 팁

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.

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.

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

String str = sdf.format(date)

Well, you can convert like this,

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

public class StringToDateDemo
{
   public static void main(String[] args) throws ParseException  
   {
      String strDate = "Apr 27, 2011 5:53:48 pm";
      SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
      Date dt = sdf.parse(strDate);
      System.out.println(dt);
   }
}

Output:

Apr 27, 2011 5:53:48 PM

Reference:

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

https://www.flowerbrackets.com/java-convert-string-to-date/

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

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top