将字符串转换为java.util.date [英] Converting string to java.util.date

查看:132
本文介绍了将字符串转换为java.util.date的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用需要转换为java.util.date对象的日期字符串。

I am working with date strings that need to be converted to java.util.date objects.

我正在使用以下代码来做到这一点:

I'm using the following code to do this:

public void setDates(String from, String to) throws ParseException
{
    Date fromDate = new Date();
    Date toDate = new Date();
    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");

    fromDate = df.parse(from);
    toDate = df.parse(to);

    this.setDepartDate(fromDate);
    this.setReturnDate(toDate);
}

问题是我必须转换的字符串值始终是(并且我对此无法控制),格式如下: 2013年9月20日。

The problem is that the string values that I have to convert are always(And I have no control over this) in the following format: "20 September, 2013".

这会导致我的函数在达到 fromDate = df.parse(from);

This causes my function to through a ParseException when it reaches fromDate = df.parse(from);

有人可以帮助我理解原因,并建议解决方案吗?

Could anyone help me understand why, and perhaps suggest a solution?

推荐答案

查看 SimpleDateFormat JavaDocs 获取可用的格式选项,但基本上,您需要将日期格式更改为类似于 dd MMMM,yyyy

Check out the SimpleDateFormat JavaDocs for the available format options, but basically, you need to change your date format to something more like dd MMMM, yyyy

try {
    String dateValue = "20 September, 2013";
    SimpleDateFormat df = new SimpleDateFormat("dd MMMM, yyyy");
    Date date = df.parse(dateValue);
    System.out.println(date);
} catch (ParseException exp) {
    exp.printStackTrace();
}

哪个输出...

Fri Sep 20 00:00:00 EST 2013

这篇关于将字符串转换为java.util.date的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆