So, I have been trying this for a long time. I need to save the date and time as a String (DD-MM-YYYY & HH:mm) in a SQLite database.
Now I have to set up my AlarmManager to show notifications, but AlarmManager takes the time and date in milliseconds.
How can I convert these into milliseconds?
What is the right way to store Date and Time in a SQLite DB?
Which is the right way to store Date and Time in sqlite ?
You might find it easier in the end to store your dates as milliseconds in your SQLite database (using SQLite's INTEGER data type). This makes it very easy to use that value for creating Calendar objects or for using it in creating an AlarmManager alarm. But if you store the date in a String format in your database, you will probably find yourself performing String manipulation on it.
If you store your date as milliseconds in your database, it is very easy to create a Calendar object from it and extract the year, month and day:
// get millis from database
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
For storing times, I find it best to store them as a 24-hour string in the "HH:MM" format. Android's TimePickers accept and return hours in 24-hour format, so this just makes life easier.
You still need to do some minimal String manipulation to get the int hours and minutes from "HH:MM", but it can be as simple as:
String timeString = "18:30";
int hours = Integer.valueOf(timeString.split(":")[0]);
int minutes = Integer.valueOf(timeString.split(":")[1]);
But if you wanted to, you could even store your times in millis as a SQLite INTEGER, then use that value to create a new Calendar object and extract the hours and minutes from it:
// get millis from database
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(millis);
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTES);
You can use SimpleDateFormat to do this:
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm");
String time = "12-01-2014 10:23";
long millis = format.parse(time).getTime();
This should work. I have something like this too, and I set an extra column where I save the milliseconds from this date inside the database, so I can get it directly.
Related
I want to store date and time that user picks through date picker and time picker on Android. By reading various thread I came to conclusion to store date and time in INTEGER format. So I'm converting them to long values using following function but when I'm converting them back to Date it is giving me wrong Date.
private DatePickerDialog.OnDateSetListener startDatePickerListener = new DatePickerDialog.OnDateSetListener(){
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String dateText = getTimeString(year,monthOfYear,dayOfMonth);
//Converting Date to long so that can be stored in DB
long date = Utility.getDateLong(year,monthOfYear,dayOfMonth);
taskModel.setStartDate(date);
startDateView.setText(dateText);
}
};
public static long getDateLong(int year, int month, int day){
Calendar cal = new GregorianCalendar(year, month, day);
long timeStamp = (cal.getTimeInMillis()+cal.getTimeZone().getOffset(cal.getTimeInMillis()))/1000;
return timeStamp;
}
To convert long value back to Date I'm using the below function :
public static String getDateFromLongValue(long d){
Date date = new Date(d);
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
String formattedDate = dateFormat.format(date);
return formattedDate;
}
But this is giving me the different date then the entered value. Is there any other way to do this. I basically need to compare dates and to find the time elapsed between two dates?
I suggest a duplicate because while "best way" is theoretically debatable, SQLite offers date functions based on the fact that SQLite doesn't have a time and date type, but does offer date functions based ISO-formatted TEXT timestamp.
One item that is definitely not a matter of opinion though is where you want to do the bulk of operations. You have two choices:
Query for a large amount of data then filter that in your app
Query for a subset of that data
You might will run into timing and memory issues if you don't pre-filter your dataset via the query (i.e. using date and time functions off an ISO-formatted text timestamp) and opt to transform epochs in Java.
In my Android App, I want to insert date from DatePicker to SQL Server DB.
The Date type in SQL Server is datetime.
I can get Day and Month and Year from DatePicker like this :
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
But how should i pass it to SQL Server 2012?
With which format?
It depends on which database you want to store. If you are storing locally in your sqlite database I will recommend store the date in millis and if you are storing in backend server you can convert it to ISO date format. Examples of both way is given below, and if you want date in any other format you can do that too by modifying string passed to constructor of STANDARD_UI_DATE_FORMAT object.
Calender startTimeCalender = Calendar.getInstance();
startTimeCalender.set(Calendar.YEAR, year);
startTimeCalender.set(Calendar.MONTH, monthOfYear);
startTimeCalender.set(Calendar.DAY_OF_MONTH, dayOfMonth);
//Date in Millis
lond dateInMillis = startTimeCalender.getTimeInMillis();
SimpleDateFormat STANDARD_UI_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-ddTHH\:mm\:ss.fffffffzzz");
//Date in ISO Format
String formattedDate = STANDARD_UI_DATE_FORMAT.format(startTimeCalender.getTime())
You can convert a string (as in the example provided by himanshu1496) to a valid datetime type on SQL Server using the CONVERT() function.
So as long as you can get the string value to the database you could do something like this:
SELECT
'2015-11-24 14:17:19' AS UnconvertedText,
CAST('2015-11-24T14:17:19' AS datetime) AS UsingCast,
CONVERT(datetime, '2015-11-24T14:17:19', 126) AS UsingConvertFrom_ISO8601 ;
GO
(Dont forget that sneaky T in the string in the example above)
It is more detailed described in the documentation here:
https://msdn.microsoft.com/en-us/library/ms187928.aspx
Save the date as miles into your SQL database.
What does this date means: 1427856000472?
I have got this date from cursor.getString(4).
I need the receiving date of the message, but its format is not clear to me.
Kindly help, and thank you very much for sharing your knowledge.
Its in time in milliseconds .. you need to convert them to proper time.. following thing is what i followed.. it will return date month and year
where timestamp is equal to your time .. eg 1427856000472
final Calendar cal = Calendar.getInstance();
java.text.DateFormat df= DateFormat.getMediumDateFormat(mCtx);
java.text.DateFormat df1=DateFormat.getTimeFormat(mCtx);
String date = (df.format(timeStamp).toString());
String time=df1.format(timeStamp);
cal.setTimeInMillis(timeStamp);
int messageYear=cal.get(Calendar.YEAR);
int month=cal.get(Calendar.MONTH);
int dates=cal.get(Calendar.DATE);
Locale locale=Locale.getDefault();
String monthName=cal.getDisplayName(Calendar.MONTH, Calendar.SHORT , locale);
String date = monthName+" "+dates+"\n"+time;
That time is the time elapsed since epoch(The Unix epoch is the number of seconds that have elapsed since January 1, 1970).
You can convert epoch time using this link:
http://www.epochconverter.com/
You can find the answer here in this post:
convert epoch time to date
Hope this helps.
I am using jxl api to read an excel file in android. When I get a date like "30/11/2012" from excel, the LabelCell output shows me date as "11/30/12".
1) I need to get the output in dd/MM/yyyy format when reading the excel file, because it exists that way in excel, so I wouldn't want to unnecessarily convert it into another format. How to do that ?
2) After reading in the excel column's date, I generate 2 variables, one which has excel date - 20 days (lets call it excelMinus20) and another excel date + 10 days (lets call it excelPlus10.
Now, I would like to check going further, if the current system date (smartphone's date) >= excelMinus20 and current system date <= excelPlus10.
How to do this whole thing using java.text.Date ? I tried using joda time as well, but it's too complicated to use. Please guide me at least in the right direction.
Thanks in advance
Omkar Ghaisas
To parse your date from text format:
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
Date date = formatter.parse("30/11/2012");
More info : SimpleDateFormat doc
To substract days from your date:
public static Date substractDays(Date date, int days)
{
long millis = date.getTime();
long toSubstract = days * 1000 * 60 * 60 * 60 * 24;
// 1milli 1s 1m 1h 1d
return new Date(millis-toSubstract);
}
Adding some days would be the same, except replace - with +
To get back a String representation from a Date object:
DateFormat formatter = new SimpleDateFormat("...pattern...");
String formatedDate = formatter.format(date.getTime());
EDIT:
You could also do the Date adding/substracting with the method you suggested:
public static Date substractDays(Date date, int days)
{
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, -20 /*or +10*/);
return calendar.getTime();
}
If you want to check if a Date is in an interval, then:
public static boolean isInInterval(Date date, Date from, Date to)
{
return date.getTime()<to.getTime() && date.getTime() > from.getTime();
}
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?
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String now = formatter.format(new Date());
Thank you,
Just use parse instead of 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 :
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
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.
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
There are these methods available to get the individual parts of a date
getDate()
getMinutes()
getHours()
getSeconds()
getMonth()
getTime()
getTimezoneOffset()
getYear()
Try using : 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.