簡體   English   中英

如何在Java中將數值轉換為日期?

[英]How to convert a numeric value to date in Java?

我有值的列表1201211201352005存儲為字符串,我需要把它們轉換為2012年1月11月2013年,2005年5月相應。 我知道如何使用解析字符串並使用if語句來做到這一點。 有什么有效的方法嗎?

這樣的事情可能會起作用:

String val = "12012";
int numVal = Integer.parseInt(val);
int year = numVal % 10000;
int month = numVal / 10000;
... create a date from that ...

我不知道您是否要使用Java DateCalendar或其他任何東西。

Calendar cal = Calendar.getInstance().clear();
cal.set(year, month-1, 1);

Date date = cal.getTime();

或Joda Time不帶時區的日期:

LocalDate dt = new LocalDate(year, month, 1);

使用SimpleDateFormat模式,您可以輕松地做到這一點:試試下面的簡單代碼:

String str="12012";//112013 , 52005
SimpleDateFormat format=new SimpleDateFormat("Myyyy");
SimpleDateFormat resFormat=new SimpleDateFormat("MMM yyyy");
Date date=format.parse(str);
System.out.println(resFormat.format(date));

正如你所代表的是兩種不同的格式Myyyy和MMyyyy日期字符串,用SimpleDateFormat ,我不知道你能避免一個if語句,這是我會怎么做:

    SimpleDateFormat sdf1 = new SimpleDateFormat("Myyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("MMyyyy");
    Date d = null;
    if(5 == s.length()){
        d = sdf1.parse(s);
    }else if(6 == s.length()){
        d = sdf2.parse(s);
    }

暫無
暫無

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

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