我怎样才能转换
Wed Apr 27 17:53:48 PKT 2011
到
Apr 27, 2011 5:53:48 PM.
new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a.").format(yourDate);
您可以使用 SimpleDateFormat 或 JodaTime 的解析器。
但是,编写自己的字符串解析器可能很简单,因为您只是重新排列字段。
SimpleDateFormat sdf = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");
String str = sdf.format(date)
您可以混合使用 JDK 和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));
}
}
注意:我已经包含了这些import
语句,以明确我正在使用哪些类。
嗯,你可以这样转换,
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);
}
}
输出:
Apr 27, 2011 5:53:48 PM
参考:
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html
您可以使用 SimpleDateFormat 将字符串转换为已定义日期表示中的日期。可以在以下位置找到 SimpleDateFormat 用法的示例:http ://www.kodejava.org/examples/19.html
new java.text.SimpleDateFormat("MMM d, yyyy h:mm:ss a").format(date);
我注意到您想要的输出没有以 0 为前缀的一天中的小时,因此您需要的格式字符串应该只有一个“h”。我猜您希望一个月中的某一天具有类似的行为,因此该模式也仅包含一个“d”。