簡體   English   中英

將字符串解析為日期

[英]Parse String to Date

String str_date = currentMonth + 1 + "-" + value.toString() + "-" + currentYear;
            DateFormat formatter ; 
            Date date = null ; 
            formatter = new SimpleDateFormat("dd-MMM-yy");
            try {
                date = (Date)formatter.parse(str_date);
            } 
            catch (ParseException e) {
                e.printStackTrace();
            }  
            System.out.println(date);

嗨,我試圖搜索迄今為止的字符串,幾乎每個人都使用這種代碼,但它似乎仍然打印出 null? 謝謝你。

嘗試

formatter = new SimpleDateFormat("dd-MM-yyyy");

或者

formatter = new SimpleDateFormat("MM-dd-yyyy");

取決於你真正想要什么。 您的代碼表明您可能希望將一個月作為模式的第一部分。

確保currentMonth + 1是您想要的。 如果currentMonth是 12,那么+1會將日期推到下一年的 1 月。

另外,也嘗試習慣使用Locale 默認的可能適合您,但會在其他人的計算機上中斷。

暫無
暫無

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

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