如何在android中以“YYYY-MM-DD”格式获取Date对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10312889/
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
How to get Date object in “YYYY-MM-DD” format in android
提问by brig
I have a requirement that I need to compare two Dates. One Date will come from DB which is String in "YYYY-DD-MM" firm and I need to compare this String Date with current Date.
我有一个要求,我需要比较两个日期。一个日期将来自数据库,它是“YYYY-DD-MM”公司中的字符串,我需要将此字符串日期与当前日期进行比较。
for this I am converting Date String into Date object.
为此,我将日期字符串转换为日期对象。
Now I need current Date also in "YYYY-MM-DD" format and it should be Date object so that I can use.compareTo() method compare two dates..
现在我还需要“YYYY-MM-DD”格式的当前日期,它应该是日期对象,以便我可以使用.compareTo()方法比较两个日期..
Please help me how to do that...
请帮我如何做到这一点...
回答by Zaz Gmy
Date cDate = new Date();
String fDate = new SimpleDateFormat("yyyy-MM-dd").format(cDate);
回答by Pallavi
Calendar c = Calendar.getInstance();
SimpleDateFormat tf = new SimpleDateFormat("yyyy-MM-dd");
String time=DB time;
Date parseTime= tf.parse(time);
Integer dayNow=c.getTime().getDate();
Integer dayDb=parseTime.getDate();
then you can compare dayNow
and dayDb
.
然后你可以比较dayNow
和dayDb
。
回答by Avi Kumar Manku
You can do it in following way
您可以通过以下方式进行
// pick current system date
Date dt = new Date();
// set format for date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// parse it like
String check = dateFormat.format(dt);
System.out.println("DATE TO FROM DATEBASE " +
arrayOfStringDate[d].toString());
System.out.println("CURRENT DATE " + check);
// and compare like
// 并比较
System.out.println("compare "+
arrayOfStringDate[d].toString().equals(check));
回答by Anthony Grist
If your current date is actually an instance of the java.util.Date
class, you don't need to specify a format for it; it's just a millisecond value that represents a specific moment in time.
如果您的当前日期实际上是java.util.Date
该类的一个实例,则无需为其指定格式;它只是代表特定时刻的毫秒值。
You can get the current date like so:
您可以像这样获取当前日期:
Date currentDate = new Date();
回答by gutiory
You can use 2 ways:
您可以使用 2 种方式:
DateFormatobject. Use parse method.
Make your own parser of the Date. I mean, you convert the year, month and day in an integer each, and use Dateconstructor to get the Date.