[英]DateTime from PHP to Java (Android): how to convert a string to a DateTime object?
在PHP中將字符串轉換為DateTime()非常容易:
$dateTime = new DateTime("2013-12-11 10:109:08");
echo $dateTime->format("d/m/Y"); // output 11/12/2013
Java中的等價物是什么? 我在stackoverflow中看到了很多問題。 我找不到解決這個問題的方法。
我的最后一次嘗試是:
SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm", Locale.ITALIAN);
return dateFormat.format(new Date(datetime)).toString();
此崩潰應用程序。 Android Studio告訴我不推薦使用Date(java.lang.String)。
有人能幫我嗎?
// First convert the String to a Date
String dateTime = "2013-11-12 13:14:15";
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ITALIAN);
Date date = dateParser.parse(dateTime);
// Then convert the Date to a String, formatted as you dd/MM/yyyy
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormatter.format(date));
如果必須處理不在默認語言環境中的TimeZones,可以讓解析器/格式化程序使用SimpleDateFromat.setTimeZone()
來考慮時區。
嘗試這個
String time1="";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss,SSS",Locale.US);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(yourmilliseconds);
time1=sdf.format(calendar.getTime());
是從JDK 1.1版開始,不推薦使用Date(java.lang.String)
並將其替換為DateFormat.parse(String s)
。
解析它:
SimpleDateFormat formatter =
new SimpleDateFormat("dd.MM.yyyy", Locale.GERMANY);
Calendar date = Calendar.getInstance();
try {
date.setTime(formatter.parse("12.12.2010"));
} catch (ParseException e) {
e.printStackTrace();
}
在這里查看我的Android日期選擇器示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.