[英]How to parse String to Date object?
I'm trying to create a date variable based on a date I have chosen. 我试图根据我选择的日期创建一个日期变量。 When I use the the simpledateformat to parse it to the date object, it will not work.
当我使用simpledateformat将其解析为date对象时,它将无法工作。 Please can someone help me?
有人可以帮我吗?
package com.example.rossr.tlatimetableweek;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.*;
import java.text.*;
public class A_Week extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a__week);
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate = new Date();
Log.i("Current Date",dateFormat.format(currentDate));
Date termDate = dateFormat.parse("11/12/2017"); //error on this line
}
}
Try this 尝试这个
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("11/12/2017")
}
catch (ParseException ex){
Log.i("Current Date","error occurred while parsing date");
}
This is because DateFormat.parse
method throws ParseException
and you need to handle it. 这是因为
DateFormat.parse
方法将引发ParseException
并且您需要对其进行处理。 declare it in the method signature or handle the exception with try and catch block. 在方法签名中声明它,或使用try and catch块处理异常。 i have modified the code to handle it with try and catch block.
我已经修改了代码以使用try和catch块进行处理。 please try with below code.
请尝试以下代码。
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date currentDate = new Date();
Log.i("Current Date",dateFormat.format(currentDate));
try {
Date termDate = dateFormat.parse("11/12/2017");
System.out.println(" date ["+termDate+"]");
}
catch (ParseException ex){
Log.i("Current Date","error occurred while parsing date");
}
You need to try/catch the ParseException. 您需要尝试/捕获ParseException。 Use:
采用:
try {
Date termDate = dateFormat.parse("11/12/2017");
} catch (ParseException e) {
e.printStackTrace();
}
Android studio suggested me this solution. Android Studio向我建议了该解决方案。 Not sure, what IDE you are using.
不知道您正在使用什么IDE。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.