Xin chào tôi có chuỗi sau: 2012-05-20T09: 00: 00.000Z và tôi muốn định dạng nó thành 20/05/2012, 9amLàm thế nào để định dạng chuỗi ngày trong java?
Làm như thế nào trong java?
Cảm ơn
Xin chào tôi có chuỗi sau: 2012-05-20T09: 00: 00.000Z và tôi muốn định dạng nó thành 20/05/2012, 9amLàm thế nào để định dạng chuỗi ngày trong java?
Làm như thế nào trong java?
Cảm ơn
sử dụng SimpleDateFormat
đầu tiên parse()
String
để Date
và sau đó format()
Date
để String
Nếu bạn đang tìm kiếm một giải pháp cho trường hợp cụ thể của bạn, nó sẽ là:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);
package newpckg;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class StrangeDate {
public static void main(String[] args) {
// string containing date in one format
// String strDate = "2012-05-20T09:00:00.000Z";
String strDate = "2012-05-20T09:00:00.000Z";
try {
// create SimpleDateFormat object with source string date format
SimpleDateFormat sdfSource = new SimpleDateFormat(
"yyyy-MM-dd'T'hh:mm:ss'.000Z'");
// parse the string into Date object
Date date = sdfSource.parse(strDate);
// create SimpleDateFormat object with desired date format
SimpleDateFormat sdfDestination = new SimpleDateFormat(
"dd/MM/yyyy, ha");
// parse the date into another format
strDate = sdfDestination.format(date);
System.out
.println("Date is converted from yyyy-MM-dd'T'hh:mm:ss'.000Z' format to dd/MM/yyyy, ha");
System.out.println("Converted date is : " + strDate.toLowerCase());
} catch (ParseException pe) {
System.out.println("Parse Exception : " + pe);
}
}
}
Ngày phải là java.util.Date, với java.sql.Date nó không hoạt động (chỉ là một lưu ý) –