java 在 Android 中设置日期和所需时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36257085/
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
Set date and desired time in Android
提问by Mew
I want to set date and time in my android app. The date should be today's date but the time should be set to 6:00 AM by default in the text field. I have read many links but most of them shows today's time and date (example: 2016-03-28 11:53:55).
我想在我的 android 应用程序中设置日期和时间。日期应为今天的日期,但默认情况下,文本字段中的时间应设置为上午 6:00。我已经阅读了很多链接,但其中大部分都显示了今天的时间和日期(例如:2016-03-28 11:53:55)。
String timetxt1 = "06:00:00";
Date datetxt1 = null;;
try {
datetxt1 = simpleDateFormat.parse(timetxt1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar selectedDate1 = Calendar.getInstance();
selectedDate1.setTime(datetxt1);
edittxt.setText(dateFormatter.format(selectedDate1.getTime()));
回答by mmuzahid
Date date = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 6);// for 6 hour
calendar.set(Calendar.MINUTE, 0);// for 0 min
calendar.set(Calendar.SECOND, 0);// for 0 sec
System.out.println(calendar.getTime());// print 'Mon Mar 28 06:00:00 ALMT 2016'
回答by Ragesh Ramesh
To get current date use below method
要获取当前日期,请使用以下方法
public static String getCurrentDate() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd", Locale.getDefault());
Date date = new Date();
return dateFormat.format(date);
}
This will give you the current date alone. And if you want the time to be 6:00AM use the below method
这将单独为您提供当前日期。如果您希望时间为早上 6:00,请使用以下方法
public static String getCurrentDateAndTime6() {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.getDefault());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE,0);
return dateFormat.format(calendar);
}
回答by Shree Krishna
I've done like this,
我做过这样的
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
date.setHours(6);
date.setMinutes(0);
date.setSeconds(0);
Log.d("DateTime", dateFormat.format(date));
OUTPUT :2016/03/28 06:00:00
输出 :2016/03/28 06:00:00