I store my values in database by converting the date value in milliseconds,so to get the latest date on top by using order by desc query. The order is coming as required but if i enter date 02/01/2016 and 01/30/2016 both are storing same milliseconds value.
String date = "02/01/2016";
String month = date.substring(0, 2);
String day = date.substring(3, 5);
String year = date.substring(6, 10);
Calendar c1 = Calendar.getInstance();
c1.set(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day));
long left = c1.getTimeInMillis();
After debugging i got the following milliseconds values
02/01/2016----61414914600000
and 01/30/2016----61414914600000
Anybody knows why this happening?
Using SimpleDateFormat value I am getting different milliseconds value:
Date date;
String dtStart = "02/01/2016";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
try {
date = format.parse(dtStart);
long timeMills=date.getTime();
System.out.println("Date ->" + date);
} catch (Exception e) {
e.printStackTrace();
}
I ran your initial code and it functions almost as expected. A few points:
You mention millisecond 61414914600000. That's not correct because it's 1900 years into the future:
http://currentmillis.com/?61414914600000
I'm pretty sure you got that number from a Date object, not from a Calendar: http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date(int, int, int)
As Mat said the month is zero-based for Calendar and the line where you call the setter should subtract 1:
c1.set(Integer.parseInt(year), Integer.parseInt(month) - 1, Integer.parseInt(day));
You answered your own question with another snippet of code but Date is deprecated, Calendar should be used instead. Your original code in the initial post was essentially correct (except the zero-based month). You should make sure that you know where your output is coming from and / or that you don't forget to build the code before running it.
Related
I want to let the user choose a Date from a DatePicker and store it into database, and then convert it to dd/mm/yyyy format.
dp =(DatePicker)findViewById(R.id.DateActivity);
setDate.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
requestDate.setText("Day" + dp.getDayOfMonth() + " Month " + (dp.getMonth() + 1)+ " Year " + dp.getYear());
}
});
The output is Day 9 Month 2 Year 2014.
The output months is less by one for every month I choose so I add 1 to the month. Why this is the case?
But the main problem is how do I convert it to 09022014 and store it in the database? If the db has the format dd/mm/yyyy does it means it will not accept my output?
java.util.Calendar treats the months as a zero-based list, so the DatePicker follows this convention as well (see the documentation for DatePicker.init). It's confusing, but that's just the way Java does it (for now, at least). Adding 1 like you're doing will work just fine.
As for converting the date, you can use the SimpleDateFormat class to format the date however you like. For what you said, the format pattern string would be "ddMMyyyy". See the sample code below:
// Build Calendar object from DatePicker fields.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, myDatePicker.getMonth());
cal.set(Calendar.DAY_OF_MONTH, myDatePicker.getDayOfMonth());
cal.set(Calendar.YEAR, myDatePicker.getYear());
// Convert date to desired format.
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyy");
String dateString = sdf.format(cal.getTime());
int dateInt = Integer.parseInt(dateString); // if you want it as an int instead
You may want to consider storing the date as 20140209 ("yyyyMMdd", year-month-day) instead for sorting purposes, as that will naturally allow it to be sorted chronologically.
For your second problem (putting it into the database) you can simply create a string like this:
String todb = dp.getDayOfMonth() + "/" + (dp.getMonth() + 1)+ "/" + dp.getYear();
Which will return a string like 09/21/2014.
Now, as for your first problem (the month being off by one), I believe this stems from a CalendarView.OnDateChangeListener. It says:
month The month that was set [0-11].
I would bet that this was also implemented on DatePicker's (or you're using the CalendarView with the DatePicker), so January is 0 and December is 11. So your way of changing the month by 1 is a perfectly fine way to do it.
I am working on an application in which I have to convert a long value to a Date string and display. To achieve the purpose I am using following function, but it is returning me the date from 70's and 80's obviously not appropriate. I am using the following finction:
public static String convertDateFromLongToCompleteString(long date) {
Date d = new Date(date * 1000);
SimpleDateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
String formattedDateFromLong = dateformat.format(d);
return formattedDateFromLong;
}
The long value is just simply System.currentTimeMillis() and when I have to show it to the user, I have to format that for which I am using above function. I have checked system and device dates, their zones and time, everything is just fine. Please update that why is this issue appearing and how can I get the exact date. Thanks!
Edit
I have also tried withoout multiplication with 1000, it gives me time and date from 1970.
If your long date is simply System.currentTimeMillis(), then multiplication with 1000 is not required.
Date d = new Date(date);
Replace Date d = new Date(date * 1000); with Date d = new Date(date);
In case you're using the above method only with System.currentTimeMillis(), you can call Date constructor without any parameters, it will give you the Date object that refers to the current date and time. This will be an easier way to solve your problem. 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 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));
In my application i have 2 field, 1 is date and another is recc(is an integer) in database table.
Now i will explain my requirement:
Consider suppose user enters today's date(26-07-2012) and recc as 10.It means that starting from today's date to that +10 date.I got that 10th date from today's date.But what i want is 10th day from today's date means it will surely go to next month also (26-07-2012----5-08-2012),but i have to know the count of date which falls in this particular month,(i.e)between 26-07-2012----5-08-2012 how many days it will fall within this month.I think i have explained my problem clearly,if not i am ready to give more explanation.Thanks in advance.
Date value:
EditText date=(EditText)findViewById(R.id.startdateexp);
String startdate=date.getText().toString();
you can do this by following way:
1. Get date from Database.
Now get day of month from the date by following method:
DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
date = iso8601Format.parse(dateTime);
} catch (ParseException e) {
Log.e(TAG, "Parsing ISO8601 datetime failed", e);
}
Calendar cal=Calendar.getInstance();
cal.setTime(date);
int currentDay= cal.get(Calendar.DAY_OF_MONTH);
calculate Last day of month by:
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
If you're using the Date class you can offset it by the number of days converted to milliseconds to create a new Date:
Date datePlusRecc = new Date(oldDate.getTime() + recc*86400000); // 86400000 = 24*60*60*1000
Note that this is useable only when recc is relatively small (< about 20), because otherwise the multiplication will overflow.
Just use the java.util.Date class combined with your date in milliseconds.
In a for loop add one day to the one version in milliseconds and convert it back to Date. Get the Month out of the Date Object and compare it with the current month. As soon as the month is a new one you have your total count of days in the current month.
Date currentDate = new Date(currentMillis);
long countingMillis = currentMillis;
int daysInSameMonth = 0;
while(true){
daysInSameMonth++; // if the actual date schould not count move this line at the button of the while
countingMillis += 1000*60*60*24;
Date dt = new Date(countingMillis);
if(currentDate.getMonth() != dt.getMonth())
break;
}