Hes*_*sam 129 string android casting date
每次应用程序启动时,我将当前时间存储在数据库中.
Calendar c = Calendar.getInstance();
String str = c.getTime().toString();
Log.i("Current time", str);
Run Code Online (Sandbox Code Playgroud)
在数据库方面,我将当前时间存储为字符串(如上面的代码所示).因此,当我从数据库加载它时,我需要将其强制转换为Date对象.我看到了一些样本,他们都使用了"DateFormat".但我的格式与日期格式完全相同.所以,我认为没有必要使用"DateFormat".我对吗?
无论如何直接将此String转换为Date对象?我想将此存储时间与当前时间进行比较.
谢谢
======> 更新
谢谢亲爱的伙计们.我使用以下代码:
private boolean isPackageExpired(String date){
boolean isExpired=false;
Date expiredDate = stringToDate(date, "EEE MMM d HH:mm:ss zz yyyy");
if (new Date().after(expiredDate)) isExpired=true;
return isExpired;
}
private Date stringToDate(String aDate,String aFormat) {
if(aDate==null) return null;
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat simpledateformat = new SimpleDateFormat(aFormat);
Date stringDate = simpledateformat.parse(aDate, pos);
return stringDate;
}
Run Code Online (Sandbox Code Playgroud)
use*_*305 380
从字符串到日期
String dtStart = "2010-10-15T09:27:37Z";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = format.parse(dtStart);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
从日期到字符串
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
try {
Date date = new Date();
String dateTime = dateFormat.format(date);
System.out.println("Current Date Time : " + dateTime);
} catch (ParseException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)
Run Code Online (Sandbox Code Playgroud)
通过使用SimpleDateFormat或DateFormat类
例如
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
Run Code Online (Sandbox Code Playgroud)
小智 5
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyClass
{
public static void main(String args[])
{
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
String dateInString = "Wed Mar 14 15:30:00 EET 2018";
SimpleDateFormat formatterOut = new SimpleDateFormat("dd MMM yyyy");
try {
Date date = formatter.parse(dateInString);
System.out.println(date);
System.out.println(formatterOut.format(date));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是您的 Date 对象日期 ,输出为:
UTC 2018 年 3 月 14 日星期三 13:30:00
2018 年 3 月 14 日
归档时间: |
|
查看次数: |
211683 次 |
最近记录: |