简体   繁体   English

Java:将字符串转换为日期

[英]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: 我正在尝试获取Talend作业中的当前日期,并将其用作上下文变量:

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. 我不知道您的context.dateout是什么意思。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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