[英]How to convert string to date format and return type must be date
我写了以下代码:
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String newDAte = String.valueOf(day) + "-" + String.valueOf(month + 1) + "-" + String.valueOf(year);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
try {
Date d = dateFormat.parse(newDAte);
System.out.println("DATE" + d);
System.out.println("Formated" + dateFormat.format(d));
d = dateFormat.parse(String.valueOf(d));
Toast.makeText(MainActivity.this, String.valueOf(d), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
System.out.println("Excep" + e);
}
当我敬酒时,它向我显示了wednesday spetember 10 2016 ...
这样的日期wednesday spetember 10 2016 ...
现在当我将其转换为字符串时,它显示出完美的输出:26-10-2016
String sdate = String.valueOf(dateFormat.format(d))
但这是作为字符串返回的,我希望作为日期类型,如:
Date newD = dateFormat.format(d);
但这是行不通的。
我想要类似26-10-2016
输出,但它必须返回/存储到Date变量中
如何返回日期类型的日期?
见下文。 这对我来说是工作。
String dateString = "26-10-2016";
convertDateFormat(dateString);
private Date convertDateFormat(String data) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date date = simpleDateFormat.parse(data);
Log.d(TAG," test==>"+date);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
输出:test ==> test ==> 2016年10月26日星期三00:00:00 GMT + 05:30(日期格式)
在这里您可以找到两个函数,可以将Millies转换为Date并将Date转换为Millies
Milles to Date格式。
private String convetTimeStamp(String time) {
Calendar cal = Calendar.getInstance();
long Time = Long.parseLong(time);
cal.setTimeInMillis(Time * 1000);
String date = DateFormat.format("dd-MM-yyyy hh:mm a", cal).toString();
return date;
}
如果您不想要时间,只需删除hh:mm a
约会到米莉
private long dateToMillies(String time)
{
Date date = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
formatter.setLenient(false);
date = formatter.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return (date.getTime()/1000);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.