Parse short US date into yyyy-MM-dd, java

2019-06-05 10:27发布

问题:

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!

回答1:

When I run this it prints

New date: 2011-03-27

I suspect your problem is nothing to do with this but rather you have a default directory for your application which is a UNC path. i.e. exactly what your error message says.

Try running this program from your C: drive or a path using a network drive letter.



回答2:

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


回答3:

You can also do it like this

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); 

To print out the time you say

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

Cheers



回答4:

I was getting the AssertionError complaining about the absolute path as well, and found a workaround through sheer brute force. I thought I would post my results here with the hopes that someone that is searching for an answer to this problem will not have to waste as much time as I did fixing it.

The problem seems to be a bug in Oracle's version of the Java VM. If you create a java.util.Calendar object (either directly or indirectly) for the first time in a non-static object, then this error occurs. To prevent it, just instantiate a Calendar object in your main() method, which is static. Subsequent non-static instantiations will work ok after that, at least in my case. Starting main() with something simple like

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

will do the trick.

Hope that helps someone.