Android 如何从日期格式“yyyy-MM-dd'T'HH:mm:ss.SSSZ”单独获取日、年、小时、分钟?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10551955/
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 the day, year, hours, min Individually from date format "yyyy-MM-dd'T'HH:mm:ss.SSSZ"?
提问by wolverine
I am doing a programme that stores the present time and date in "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
this format. and I am storing it in database as a string. when i am collecting the data i need the individual values like day, year, min, seconds etc.. how can i do this?
我正在做一个程序,以"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
这种格式存储当前时间和日期。我将它作为字符串存储在数据库中。当我收集数据时,我需要诸如日、年、分钟、秒等的单个值。我该怎么做?
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String now = formatter.format(new Date());
Thank you,
谢谢,
采纳答案by Joel Skrepnek
I'm suggesting that you store times in the DB as "timeInMillis". In my experience it simplifies code and it allows you to compare times values to eachother.
我建议您将数据库中的时间存储为“timeInMillis”。根据我的经验,它简化了代码,并允许您将时间值相互比较。
To store a time:
存储时间:
Calendar calendar = Calendar.getInstance(); // current time
long timeInMillis = calendar.getTimeInMillis();
mDb.saveTime (timeInMillis); // adjust this to work with your DB
To retrieve a time:
检索时间:
long timeInMillis = mDb.getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis (timeInMillis);
int milliSeconds = calendar.get(MILLISECOND);
//etc
回答by Estragon
Just use parse instead of format :
只需使用 parse 而不是 format :
String dateFromDB = "";
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date yourDate = parser.parse(dateFromDB);
And then you can can read any field you want using java.util.Date & Calendar API :
然后您可以使用 java.util.Date & Calendar API 读取您想要的任何字段:
Calendar calendar = Calendar.getInstance();
calendar.setTime(yourDate);
calendar.get(Calendar.DAY_OF_MONTH); //Day of the month :)
calendar.get(Calendar.SECOND); //number of seconds
//and so on
I hope it fits your needs
我希望它符合您的需求
回答by Basher51
Try using : int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
尝试使用: int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
Here,
这里,
- Calendar.HOUR_OF_DAY gives you the 24-hour time.
- Calendar.HOUR gives you the 12-hour time.
- Calendar.HOUR_OF_DAY 为您提供 24 小时制时间。
- Calendar.HOUR 为您提供 12 小时的时间。
回答by WingDev
There are these methods available to get the individual parts of a date
有这些方法可用于获取日期的各个部分
getDate()
getMinutes()
getHours()
getSeconds()
getMonth()
getTime()
getTimezoneOffset()
getYear()