簡體   English   中英

根據所需的日期格式將字符串更改為日期

[英]change string to date as per the required date Format

我必須得到一個日期類型的日期,而不是字符串。 我有這個代碼:

DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date1 = new Date();
String date = (formatter.format(date1));
// At this point I get the date in correct format i.e  05/24/11

Date todaysDate = (Date)formatter.parse(date);
// But after this I get the date in format : Tue May 24 00:00:00 EDT 2011
// whereas I Want to get the date like above i.e  05/24/11 
// And in type Date, not in type String 

如果有人可以幫忙,謝謝

Date object 僅代表一個時間點,沒有格式(或時區)的概念。 如果您打印出Date object 它首先使用EEE MMM dd HH:mm:ss zzz yyyy的默認格式將其轉換為String 如果您在打印時需要特定格式或以其他方式將其表示為String ,則需要像已有的一樣使用格式化程序。

換句話說,您希望Date.toString()返回與DateFormat.format()相同的內容嗎? 你可以這樣做:

public class MyDate extends Date {
    DateFormat formatter = new SimpleDateFormat("MM/dd/yy");

    public String toString() {
        return this.formatter.format(this);
    }
}

但是您真的想將演示文稿(日期格式)與您的數據混為一談嗎?

這里沒有問題,您有一個 Date 表示並且可以像現在一樣將其保存到 DB 中。 如果您將它打印到控制台,它會根據默認規則進行格式化,這就是為什么您認為它與您需要的不同,但它實際上已經具有正確的值。

因此,只需將 go 放在前面並將其放入您的數據庫中。

您的數據庫可能會保留獲取時間戳,在這種情況下,您可以創建一個:

Date d = ...
java.sql.Timestamp ts = new java.sql.Timestamp(d.getTime());

並保存這個。

暫無
暫無

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

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