2013-04-08 59 views
0

我有这两个方法,现在写。随着情况的发展,当我从数据库中获取数据字段时,它是BigDecimal格式。所以我决定为它写一个测试(formatDate()方法)。我将BigDecimal传递给该方法,但似乎我写了一些错误的代码。从我在例子和SimpleDateFormat API中看到的,我认为我已经正确地编写了代码,但是我似乎无法弄清楚如何让它抛出parseEx。有人能给我提示发生了什么吗?SimpleDateFormatter抛出ParseException

private void loadMap() { 
    //TODO: Uncomment when finished testing. 
    //DO OTHER STUFF 
    BigDecimal bd = new BigDecimal(12051998); 
    System.out.println(formatDate(bd)); 
} 

private String formatDate(BigDecimal bd) { 
    String value = bd.toString(); 
    SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); 
    try { 
     return format.parse(value); 
    } catch (ParseException pEx) { 
     logger.error(pEx); 
     return "Bad Date Format"; 
    } 
} 

由于提前,向那,

  • 约什
+2

'BigDecimal'是用于保持日期值的奇数选择。 – GriffeyDog 2013-04-08 14:40:23

+0

@GriffeyDog它是AS/400上用于DB2的IBM/Genelco软件。一切都很奇怪。 – ResourceReaper 2013-04-08 14:44:15

+0

答案是好的,但你也可以考虑使用[乔达时间](http://joda-time.sourceforge.net/userguide.html) – durron597 2013-04-08 14:50:43

回答

5
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy"); 

应该是

SimpleDateFormat format = new SimpleDateFormat("MMddyyyy"); 

return format.parse(value); // 值应是日期类型不是字符串

试试这个将日期的格式从MMddyyyy更改为MM/dd/yyyy:它对我来说工作正常。

public static void main(String[] args) throws ParseException { 
    BigDecimal bd = new BigDecimal(12051998); 
    String s = bd.toString(); 
    System.out.println(s); 
    DateFormat originalFormat = new SimpleDateFormat("MMddyyyy"); 
    DateFormat targetFormat = new SimpleDateFormat("MM/dd/yyyy"); 
    Date date = originalFormat.parse(s); 
    String formattedDate = targetFormat.format(date); 
    System.out.println(formattedDate); 
} 

输出:

12051998 
12/05/1998 
+0

我已经更新了方法到MMddyyyy我得到的消息是:无法解析的日期:“12051998” – ResourceReaper 2013-04-08 14:43:32

+0

@JoshGooding您想将日期的格式从MMddyyyy更改为MM/dd/yyyy? – 2013-04-08 14:47:33

+0

是的,我想将12051998转换为12/05/1998。有效。我不知道我必须在日期基本上进行双重转换。我尝试了一步,并没有意识到。似乎你无法一步到位。谢谢! – ResourceReaper 2013-04-08 15:31:11

相关问题