1

I want to parse the date "3/27/11" which I think is equal to US short date.

DateFormat df1 = new SimpleDateFormat("MM/dd/yy");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) df1.parseObject("03/27/11");
System.out.println("New date: " + df2.format(date));

I found the code above in several java tutorials but it doesn't seem to work. For some how I get,

Exception in thread "main" java.lang.AssertionError: Default directory must be absolute/non-UNC

Here is what I want to achieve,

input: 3/27/11
(03/27/11 should also be a valid input)
output: 2011-03-27

Thanks in advance!

4

4 回答 4

2

当我运行它时,它会打印

New date: 2011-03-27

我怀疑您的问题与此无关,而是您的应用程序有一个默认目录,即 UNC 路径。即正是你的错误信息所说的。

尝试从您的 C: 驱动器或使用网络驱动器号的路径运行此程序。

于 2011-05-17T07:40:35.117 回答
1
public class date {


    public static void main(String args[])
    {
        String s="03/27/2011";// or 3/27/2011

        SimpleDateFormat dateFormatter=s.length()==9?new SimpleDateFormat("M/dd/yyyy"):new SimpleDateFormat("MM/dd/yyyy");
        try {
            Calendar calendar=Calendar.getInstance();
            Date date=dateFormatter.parse(s);
            calendar.setTime(date);
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String str=simpleDateFormat.format(calendar.getTime());
            System.out.println(str);
        } catch (ParseException e) {
              e.printStackTrace();
        }
    }

}

    enter code here
于 2011-05-17T07:46:35.100 回答
1

你也可以这样做

String DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";

//Instance of the calender class in the utill package
Calendar cal = Calendar.getInstance(); 

//A class that was used to get the date time stamp
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); 

打印出你说的时间

System.out.println(sdf.format(cal.getTime()) );

干杯

于 2011-05-17T07:50:22.980 回答
0

我也AssertionError抱怨绝对路径,并通过纯粹的蛮力找到了解决方法。我想我会在这里发布我的结果,希望正在寻找这个问题的答案的人不会像我修复它那样浪费太多时间。

这个问题似乎是 Oracle 版本的 Java VM 中的一个错误。java.util.Calendar如果您第一次在非静态对象中创建对象(直接或间接),则会发生此错误。为了防止它,只需在您的main()方法中实例化一个 Calendar 对象,它是静态的。此后,至少在我的情况下,后续的非静态实例化将正常工作。用一些简单的东西开始 main()

System.out.println(java.util.Calendar.getInstance().getTime());

会成功的。

希望对某人有所帮助。

于 2013-06-28T13:46:59.470 回答