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.
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.
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.
I want to insert date in a table with type Date not String ( as I have to sort it later). I can't use function put() of content values because it takes only (String, String) arguments, not date. So how can I insert the current date of the system in a table row? Help Please.
public long createEntry (String name, String db_dr, int amount, Date dt){
ContentValues values = new ContentValues ();``
values.put(DbOpenHelper.ENTRY_NAME, name );
values.put(DbOpenHelper.DR_CR, db_dr );
values.put(DbOpenHelper.ENTRY_AMOUNT, amount);
values.put(DbOpenHelper.DATE, dt); // function put defined for (string, string)
long insertid= database.insert(DbOpenHelper.TABLE_ENTRIES, null, values);
return insertid;
}
SQLite doesn't support a Date datatype. What you could do, instead, is store the date in Unix time. If the date is stored in a Calendar, use getTimeInMillis, for example.
you can insert the date as milesecond. As your comment says you were able to store the date using milis and facing problem to retreive it and convert it to date. Here is an example
Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(date_in_milis);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int day = calendar.get(Calendar.DAY_OF_WEEK);
It will set the year, months, date and day as integer. So by some calculation you can format as a string if you want to get month/day name also.
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 want to have a search between specific dates. Say for example from the 1st of Aug 2012 to 13th Aug 2012. Search on this criteria gives me the entered value in the DB. If I make it 2nd Aug 2012, the query returns me null...Even weirder is that when I select 10th, 11th or the 12th Dates it works fine and gives me results...I have gone crazy trying to know where the issue could be and debug has not lead me any where....Help please?
/**query to get the details by giving all the dates/
public Cursor getName_Intime_Outtime_Date(String fromdate,String todate)
{
Log.d("pavan","in side the getnameintime out time date() of visistor adapter");
return this.db.query(DATABASE_TABLE_VISITOR,
new String[]{KEY_NAME,KEY_CHECKIN,KEY_CHECKOUT,KEY_DATE},
KEY_DATE + " BETWEEN ? AND ?",
new String[] {fromdate ,todate},
null, null, null, null);
}
Sqlite doesn't have a data type for dates. Probably you save your date as TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS").
I recommend you save date fields in your table as sqlLite datatype INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC, or as BIGINT (long java time version in miliseconds).
This way you would have a corect value returned when using BETWEEN with numbers.
EDIT
You can manage your date string from your query using date and time functions. This means you can still use your dates as strings, but performing casts to "DATE" using conversion functions when stringDates are used in sql WHERE clause.
try this, it is working for me, SELECT * FROM table_name
where substr(column_name,7)||substr(column_name,4,2)||substr(column_name,1,2)
between 'YYMMDD' and 'YYMMDD' , dates should be in reverse order eg: if date format is DD/MM/YY or DD-MM-YY , you can use 'YYMMDD'
Thank you guys for really looking into this...Finally solved this using idea found in this link https://groups.google.com/forum/?fromgroups#!topic/android-developers/Ey_4rBZx2t0%5B1-25%5D ....to summarize what I did was take a Calendar object, retrieve the current date using the Calendar object, the retrieved data is given to a simpledateformat object and comparisons to be made on that....Here is the sample code...
int test = date_pick.getMonth()+1;
Toast.makeText(getBaseContext(), "Date seleted month"+test+"/"+date_pick.getDayOfMonth()+"/"+date_pick.getYear(), Toast.LENGTH_LONG).show();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(Calendar.YEAR, date_pick.getYear());
cal.set(Calendar.MONTH, test);
cal.set(Calendar.DAY_OF_MONTH, date_pick.getDayOfMonth());
/* retriving the yyyy mm dd values here*/
set_year = cal.get(Calendar.YEAR);
set_month= cal.get(Calendar.MONTH);
set_day = cal.get(Calendar.DAY_OF_MONTH);
Log.d("kunal","datesis "+set_year+" "+set_month+" "+set_day);
string_date = set_year+"-"+set_month+"-"+set_day;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
try {
d1 = sdf.parse(string_date);
Log.d("kunal","date came "+d1);
System.out.println(sdf.format(d1));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
date_txt.setText(sdf.format(d1));