我想在Android中获取当前时间。它应该显示为下午2:30,并且我想将其存储在数据库中。我搜索了很多,但我不知道如何做到这一点。我该怎么办?
我要在Android上获取当前时间并将其格式化为“下午2:30”的形式,然后将其存储在数据库中。我已经进行了大量的搜索和尝试,但是仍然无法实现。请问如何解决这个问题?我想在Android中获取当前时间。它应该显示为下午2:30,并且我想将其存储在数据库中。我搜索了很多,但我不知道如何做到这一点。我该怎么办?
我要在Android上获取当前时间并将其格式化为“下午2:30”的形式,然后将其存储在数据库中。我已经进行了大量的搜索和尝试,但是仍然无法实现。请问如何解决这个问题?Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT+1:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("HH:mm a");
// you can get seconds by adding "...:ss" to it
date.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
String localTime = date.format(currentLocalTime);
TimeZone.getTimeZone("GMT+1:00")
更改为您自己的需要即可。 - Ahmad String Time = java.text.DateFormat.**getTimeInstance()**.format(new Date());
//and for to get date try it as below
String date_L = java.text.DateFormat.**getDateInstance()**.format(new Date());
要以12小时格式获得时间,请尝试使用“KK”替换“HH”代码。您可以在此处获取有关可用符号的完整解释。
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-4:00"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("KK:mm");
date.setTimeZone(TimeZone.getTimeZone("GMT-4:00"));
String localTime = date.format(currentLocalTime);
int currentHour = cal.get(Calendar.HOUR);
int currentMinutes = cal.get(Calendar.MINUTE);
int currentSeconds = cal.get(Calendar.SECOND);
以下方法可以按指定日期格式获取当前日期和时间
/**
* getCurrentTime() it will return system time
*
* @return
*/
public static String getCurrentTime() {
//date output format
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Calendar cal = Calendar.getInstance();
return dateFormat.format(cal.getTime());
}// end of getCurrentTime()
String currentDateAndTime = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(new Date());
很简单,您可以解析时间以获取当前时间的各个值,方法如下:
Calendar cal = Calendar.getInstance();
int millisecond = cal.get(Calendar.MILLISECOND);
int second = cal.get(Calendar.SECOND);
int minute = cal.get(Calendar.MINUTE);
//12 hour format
int hour = cal.get(Calendar.HOUR);
//24 hour format
int hourofday = cal.get(Calendar.HOUR_OF_DAY);
当您需要当前时间时,请使用数字时钟小部件:
Calendar mCalendar;
private final static String m12 = "h:mm aa";
private final static String m24 = "k:mm";
private FormatChangeObserver mFormatChangeObserver;
private Runnable mTicker;
private Handler mHandler;
private boolean mTickerStopped = false;
String mFormat;
或者查看这个教程。
你可以使用:
Calendar c = Calendar.getInstance();
int seconds = c.get(Calendar.SECOND);
您可以通过以下方式获取时间:
Date dt = new Date();
int hours = dt.getHours();
int minutes = dt.getMinutes();
int seconds = dt.getSeconds();
并且为了存储在数据库中,阅读SQLite教程此处
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
Date date = Calendar.getInstance().getTime();
String sDate = format.format(date);//31-12-9999
int mYear = c.get(Calendar.YEAR);//9999
int mMonth = c.get(Calendar.MONTH);
mMonth = mMonth + 1;//12
int hrs = c.get(Calendar.HOUR_OF_DAY);//24
int min = c.get(Calendar.MINUTE);//59