簡體   English   中英

將java.sql.timestamp從yyyy-MM-dd hh:mm:ss轉換為MM-dd-yyyy hh:mm:ss

[英]Convert java.sql.timestamp from yyyy-MM-dd hh:mm:ss to MM-dd-yyyy hh:mm:ss

有沒有一種簡單的方法可以將格式為yyyy-MM-dd hh:mm:ss的時間戳字段轉換為格式為MM-dd-yyyy hh:mm:ss的字符串。 我能夠使用substr做到這一點,但想知道是否存在轉換它的簡便方法。 謝謝!

首先... DateTimestamp對象具有其自己的格式 ,因此您不必關心存儲方式, 您需要在顯示它時立即更改格式,而不是在存儲時更改格式

當您需要顯示/打印時,請使用SimpleDateFormat ,例如,如果您想以自己的格式( MM-dd-yyyy hh:mm:ss )顯示Timestamp ,則必須這樣做:

SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
System.out.println("My date formatted is: " + sdf.format(timestamp));

您可以使用SimpleDateFormat

范例:

SimpleDateFormat input = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date d = input.parse("your date string goes here");

SimpleDateFormat output = new SimpleDateFormat("MM-dd-yyyy hh:mm:ss");
System.out.println(output.format(d));  // will return date as string in format MM-dd-yyyy hh:mm:ss 
private static String format(Date sourceDate) throws ParseException {
    SimpleDateFormat dateTimeFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

    Calendar calendar = Calendar.getInstance();

    calendar.setTime(sdf.parse(sourceDate));

    return dateTimeFormat.format(calendar.getTime());
}

使用SimpleDateFormat嘗試這樣:

DateFormat d = new SimpleDateFormat("MM-dd-yyyy HH:mm");
String str= d.format(timestamp);
System.out.println(str);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM