简体   繁体   中英

Java: Converting String to Date

I am trying to get the current date in a Talend job and I am using this as my context variable:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
context.dateout = dateFormat.format(date);

System.out.println(context.dateout);

However, the type of the result is a String and not a Date. How should I correct it?

Thank you very much!!

Try to do that according the following code:

String string = "2016-03-15";
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
try {
    Date date = dateFormat.parse(string);
    System.out.println(date);
} catch (ParseException ex) {
    System.out.println(ex);
}

I don't know what your context.dateout means.

Note the difference between parse and format.

This is to create a string from a date:

dateFormat.format(date);

This is to create a date from a string:

dateFormat.parse(dateString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM