简体   繁体   English

如何从字符串转换为日期?

[英]How to convert from String to Date?

I am getting the date (which is varchar in database) from database.我正在从数据库中获取日期(数据库中的 varchar)。 I want to use this String as a date.我想将此字符串用作日期。 the String format is "yyyy-mm-dd".字符串格式为“yyyy-mm-dd”。 How will it be converted to actual date type?它将如何转换为实际的日期类型?

Two suggested options:两个建议的选项:

Personally I'm a big fan of Joda Time (and not a big fan of the JDK classes) but as you're running on Android, you may not like the size of Joda Time.我个人是 Joda Time 的忠实粉丝(而不是JDK 类的忠实粉丝),但是当您在 Android 上运行时,您可能不喜欢 Joda Time 的大小。 (You could build your own cut-down version, admittedly.) (诚然,您可以构建自己的精简版本。)

You can try this,你可以试试这个

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDateDemo
{
    public static void main(String[] args) throws ParseException
    {
       String strDate = "2014-05-23";
       SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
       Date dt = sdf.parse(strDate);
       System.out.println(dt);
    }
}

For more on string to date in java with example refer links below,有关 java 中迄今为止字符串的更多信息,请参阅下面的链接,

https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html https://www.flowerbrackets.com/java-convert-string-to-date/ https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html https://www.flowerbrackets.com/java-convert-string-to-date/

Use the SimpleDateFormat:使用 SimpleDateFormat:

Date date = new SimpleDateFormat("yyyy-MM-dd").parse(string);

Use SimpleDateFormat object and call the parse(String source) method to convert it back to date.使用SimpleDateFormat object 并调用parse(String source)方法将其转换回日期。 Your date format will be yyyy-MM-dd .您的日期格式将为yyyy-MM-dd Example:例子:

String dateString = "2010-04-06";
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dateString);

Use this example使用这个例子

try {  String str_date="11-June-07";
 DateFormat formatter ; 
 Date date ; 
  formatter = new SimpleDateFormat("dd-MMM-yy");
  date = (Date)formatter.parse(str_date);  
 System.out.println("Date is " +date );
  } catch (ParseException e)
  {System.out.println("Exception :"+e);  }  

 }

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

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