将字符串转换为 java.sql.Date 和 java.sql.Time

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2980583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:12:24  来源:igfitidea点击:

Convert String to java.sql.Date and java.sql.Time

javadatetimejdbc

提问by Mr Morgan

If I have a method like this:

如果我有这样的方法:

public static String convertDateTimeToString(DateTime dt) {
    return dt.getDate() + " " + dt.getTime();
}

Which takes a DateTimeobject of my own which contains a java.sql.Dateand a java.sql.Time, what is the best way of reversing the process so that I can substring a java.sql.Dateand a java.sql.Timefrom a String?

它需要一个DateTime我自己的对象,其中包含 ajava.sql.Date和 a java.sql.Time,逆转该过程以便我可以从字符串中子字符串 ajava.sql.Date和 a的最佳方法是java.sql.Time什么?

Or if DateTime dtis a JodaTime DateTimeobject?

或者如果DateTime dt是 JodaTimeDateTime对象?

If this can be done without reference to java.util.Date.

如果这可以在不参考java.util.Date.

回答by Roman

Look at SimpleDateFormatclass. Here's a tutorial.

查看SimpleDateFormat类。这是一个教程

You'll need something like this:

你需要这样的东西:

String datetimeString;
Date result;
SimpleDateFormat formatter = new SimpleDateFormat("EEE d MMM yy hh:mm:ss");
result = formatter.parse (datetimeString);

回答by Behrang Saeedzadeh

You can use the valueOfmethod of java.sql.Time to convert a String into a java.sql.Time, and use the valueOfmethod of java.sql.Date to convert a String into a java.sql.Date

可以使用java.sql.Time的valueOf方法将String转换为java.sql.Time,使用java.sql.Date的valueOf方法将String转换为java.sql.Date