I want to save system date on my database, but it returns : 22/0/2013.
here my code :
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month_ = cal.get(Calendar.MONTH);
int day_ = cal.get(Calendar.DATE);
String FullDate = (""+day_+"/"+month_+"/"+year);
String text_Rate=(String.valueOf(FullDate));
Log.d("System Date show", text_Rate);
where i'm doing wrong.
This is the correct behavior. The Java Calendar month is 0-based (January is 0, December is 11).
If you really want to store it as 22/1/2013, simply add +1 to your month:
int month_ = cal.get(Calendar.MONTH) + 1;
you should save dates as long to sqlite. that is easier and less prone to errors. see here for calendar to long.
Related
I want to show the date picker Dialog on Android. Now I can choose only Normal Date. How I can convert it to hijri(islamic) Calendar? Here is the code I am using to show the Dialog,
Code to Show Date-picker Dialog
private void showDOBPickerDialog(Context context, String DateString) {
try {
String defaltDate = getCurrentDate_MMDDYYYY();
if (DateString == null || DateString.isEmpty() || DateString.length() < 10)
DateString = defaltDate;
int monthOfYear, dayOfMonth, year;
monthOfYear = Integer.parseInt(DateString.substring(0, DateString.indexOf("/"))) - 1;
dayOfMonth = Integer.parseInt(DateString.substring(DateString.indexOf("/") + 1, DateString.lastIndexOf("/")));
year = Integer.parseInt(DateString.substring(DateString.lastIndexOf("/") + 1));
DatePickerDialog datePickerDialog = new DatePickerDialog(context, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
monthOfYear = monthOfYear + 1;
String Month = String.valueOf(monthOfYear), Day = String.valueOf(dayOfMonth);
if (monthOfYear < 10)
Month = "0" + monthOfYear;
if (dayOfMonth < 10)
Day = "0" + dayOfMonth;
String selectedDate = Month + "/" + Day + "/" + year;
edtTxtDateOfId.setText(selectedDate);
}
}, year, monthOfYear, dayOfMonth);
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
} catch (Exception e) {
}
}
To get the Current Date,
public static String getCurrentDate_MMDDYYYY() {
String DATE_FORMAT_NOW = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
Calendar cal = GregorianCalendar.getInstance(Locale.FRANCE);
cal.setTime(new Date());
return sdf.format(cal.getTime());
}
As you don't want a library and need only native code, you can take a look at the source code of this implementation: https://github.com/ThreeTen/threetenbp/tree/master/src/main/java/org/threeten/bp/chrono
Take a look at the HijrahChronology, HijrahDate and HijrahEra classes, perhaps you can get some ideas and see how all the math is done to convert between this calendar and ISO8601 calendar.
But honestly, IMO calendars implementations are too complex and in most cases are not worth the trouble to do it by yourself. That's one of the cases where adding a library is totally worth it.
Using the ThreeTen-Backport lib - and configuring it to use with Android - will give you an easy way to convert the dates and also to format them:
// get ISO8601 date (the "normal" date)
int dayOfMonth = 20;
int monthOfYear = 3;
int year = 2018;
// March 20th 2018
LocalDate dt = LocalDate.of(year, monthOfYear, dayOfMonth);
// convert to hijrah
HijrahDate hijrahDate = HijrahDate.from(dt);
// format to MM/DD/YYYY
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
String formatted = formatter.format(hijrahDate); // 07/03/1439
You can also call HijrahDate.now() to directly get the current date.
And you can convert the hijrahDate back to a "normal" date with LocalDate.from(hijrahDate).
You can also use time4j:
// get ISO8601 date (the "normal" date)
int dayOfMonth = 20;
int monthOfYear = 3;
int year = 2018;
PlainDate dt = PlainDate.of(year, monthOfYear, dayOfMonth);
// convert to Hijri, using different variants
HijriCalendar hijriDateUmalqura = dt.transform(HijriCalendar.class, HijriCalendar.VARIANT_UMALQURA);
HijriCalendar hijriDateWest = dt.transform(HijriCalendar.class, HijriAlgorithm.WEST_ISLAMIC_CIVIL);
// format to MM/DD/YYYY
ChronoFormatter<HijriCalendar> fmt = ChronoFormatter.ofPattern("MM/dd/yyyy", PatternType.CLDR, Locale.ENGLISH, HijriCalendar.family());
String formatted = fmt.format(hijriDateUmalqura); // 07/03/1439
// get current date
HijriCalendar now = HijriCalendar.nowInSystemTime(HijriCalendar.VARIANT_UMALQURA, StartOfDay.MIDNIGHT);
// convert back to "normal" date
PlainDate date = hijriDateUmalqura.transform(PlainDate.class);
Taking into account your statement given in one comment that you only want a native solution and reject any extra library, I would advise to use ICU4J-class IslamicCalendar.
Sure, you have then to accept two major disadvantages:
API-level 24 (not so widespread on mobile phones)
Old-fashioned API-style (for example not immutable)
Another disadvantage (which is only relevant if you are also interested in the clock time) is the fact that ICU4J does not support the start of Islamic day in the evening at sunset on previous day. This feature is only supported in my lib Time4J, nowhere else. But you have probably no need for this feature in a date picker dialog.
Advantages:
API-style similar to what is "traditional" in package java.util, so I assume that you are got accustomed to it (but many/most people see the style rather as negative, you have to make your own decision)
at least umalqura-variant-variant of Saudi-Arabia is offered (note: other libs like Threeten-BP or Joda-Time-Android do NOT offer that variant)
acceptable or even good degree of internationalization (also better than in ThreetenBP or Joda-Time-Android)
For completeness, if you are willing to restrict your Android app to level 26 or higher only then you can also use java.time.chrono.HijrahChronology. But I think this is still too early in year 2018 because the support of mobile phones for level 26 is actually very small. And while it does offer the Umalqura variant (of Saudi-Arabia), it does not offer any other variant.
Else there are no native solutions available. And to use only native solutions is a restriction, too, IMHO.
Convert current date to hijri date
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
sdf.applyPattern("dd");
int dayOfMonth = Integer.parseInt(sdf.format(date));
sdf.applyPattern("MM");
int monthOfYear = Integer.parseInt(sdf.format(date));
sdf.applyPattern("yyyy");
int year = Integer.parseInt(sdf.format(date));
// Now
LocalDate dt = LocalDate.of(year, monthOfYear, dayOfMonth);
// convert to hijrah
HijrahDate hijrahDate = HijrahDate.from(dt);
// format to MM/DD/YYYY
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy");
I am new to Android.I have a requirement, I have a field to enter the Date Of Birth of a person.On successful selection I wanna return the total number of months from the DOB to current date.For example, if I entered DOB as 19/10/2012 I wanna return 36(months).I searched for this, but didn't find anything suitable to my requirement.Here is my current code which return sucessful data,
private void showDate(int year, int month, int day) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day);
Date date = cal.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
if(System.currentTimeMillis() > date.getTime()) {
edtDate.setText(sdf.format(date));
LocalDate date1 = new LocalDate(date);
LocalDate date2 = new LocalDate(new java.util.Date());
PeriodType monthDay = PeriodType.yearMonthDayTime();
Period difference = new Period(date1, date2, monthDay);
int months = difference.getMonths();
months=months + 1;
System.out.println("16102015:Nunber of Months"+months);
}else{
Toast.makeText(mActivity,getResources().getString(R.string.date_validationmsg),Toast.LENGTH_LONG).show();
}
}
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
To start with, I'd suggest using LocalDate instead of DateTime for the computations. Ideally, don't use java.util.Date at all, and take your input as LocalDate to start with (e.g. by parsing text straight to that, or wherever your data comes from.) Set the day of month to 1 in both dates, and then take the difference in months:
private static int monthsBetweenDates(LocalDate start, LocalDate end) {
start = start.withDayOfMonth(1);
end = end.withDayOfMonth(1);
return Months.monthsBetween(start, end).getMonths();
}
UPDATE 1
see this link the OP is accepted the same answer because Months.monthsBetween() method is not working proper for him
UPDATE 2
LocalDate userEnteredDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(date));
LocaleDate currentDate = LocalDate.parse( new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
int months = monthsBetweenDates(userEnteredDate, currentDate)
Using Joda-time library here, I was able to get the desired result.
Try the below code it would give the desired the difference in months.
DateTime date1 = new DateTime().withDate(2012, 10, 19);
DateTime today = new DateTime().withDate(2015, 10, 19);
// calculate month difference
int diffMonths = Months.monthsBetween(date1.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();
Using JodaTime, it's really easy:
http://www.joda.org/joda-time/apidocs/
int nMonths = new Period(startTime, endTime).getMonths();
Use this code to calculate months between two dates
public static int monthsBetweenUsingJoda(Date d1, Date d2) {
return Months.monthsBetween(new LocalDate(d1.getTime()), new LocalDate(d2.getTime())).getMonths();
}
I am getting date and time from DatePicker and TimePicker like:
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth() + 1;
int year = date.getYear();
int hour = time.getCurrentHour();
int minutes = time.getCurrentMinute();
But i want date and time like this format:
Friday, December 14,2012 - 4:30 PM.
Any help?
formate it as you want ....
public void SetMyCustomFormat()
{
// Set the Format type and the CustomFormat string.
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "put your formate here ";
}
for more help
http://msdn.microsoft.com/en-us/library/system.windows.forms.datetimepicker.customformat.aspx
You could try to use SimpleDateFormat, see SimpleDateFormat
Under the examples section is a date that represents your required format.
You need to create a Date Object first from Calendar, you can do as below:
Calendar cal= Calendar.getInstance();
cal.setTime(new Date());
int dateofmonth = date.getDayOfMonth();
int month = date.getMonth();
int year = date.getYear();
cal.set(dateofmonth, month, year);
Now create a SimpleDateFormat object, with the format, you desire, and format date with that format, by
String formattedDate=simpleDateFormat.format(cal.getTime());
If all you need is formatting a Date object in the current locale, you can use DateFormat:
Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, picker.getYear());
...
String str = DateFormat.getDateTimeInstance().format(date);
The method getDateTimeInstance() returns the preferred display for the current locale, which is desirable to internationalize your application because different locales have different preferences for the order of the components. For example:
US: Friday, December 14,2012 - 4:30 PM
Italy: Venerdì 14 Dicembre 2012, 16:30
In my app I have a date saved in a remote database that I want the date picker to be set to. I've researched and only found examples of setting the datepicker today's date via Calender java util. Example:
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
How can I use the Calendar to display my date from the database and not today's date? Do you have any suggestions or examples I can follow?
Update:
After experimenting with Calendar I tried to use
// set Date
String eventYear =date.substring(0,4);
String eventDay =date.substring(5,7);
String eventMonth =date.substring(8,10);
//convert string to int for because calendar only takes int: set(int,int)
int month = Integer.parseInt(eventMonth);
final Calendar c = Calendar.getInstance();
mMonth=c.get(c.set(Calendar.MONTH, Calendar.month));
// or mMonth=c.get(Calendar.MONTH, Calendar.month);
Generates error that says cannot convert int to void.
How can I use Calendar to set it to a specific date? According to google's developers site I should be able to do this.
http://developer.android.com/reference/java/util/Calendar.html
example:
set(Calendar.MONTH, Calendar.SEPTEMBER)
I'd like the date to be display in the datepicker from the server as a default value.
U can use the updateDate(year, month, day_of_month);
date picker returns integer values of day, month and year. so the parameters must be integer values. and the integer value for the month jan in the date picker is 0.
i needed to put the date extracted from a database into a datepicker. I wrote the following code and it works.
DatePicker DOB;
SQLiteDatabase db;
DOB=(DatePicker)findViewById(R.id.datePicker1);
db = openOrCreateDatabase("BdaySMS", SQLiteDatabase.CREATE_IF_NECESSARY, null);
Cursor cur = db.rawQuery("select * from BdaySMS where ph='"+pn+"';", null);//pn is the phone no.
if(cur.moveToFirst())
{
name.setText(cur.getString(0));
phone.setText(cur.getString(1));
DOB.updateDate(Integer.parseInt(cur.getString(4)),Integer.parseInt(cur.getString(3)),Integer.parseInt(cur.getString(2)));
message.setText(cur.getString(5));
}
Use JodaTime
Here's a simple example of how I set a DatePicker and TimePicker from a DateTime object, which could be the current date or any date from the past or future (the attribute in this case is called inspected_at):
DatePicker dp = (DatePicker) findViewById(R.id.inspected_at_date);
TimePicker tp = (TimePicker) findViewById(R.id.inspected_at_time);
DateTime inspected_at = DateTime.now().minusYears(1); // Typically pulled from DB.
int year = inspected_at.getYear() ;
int month = inspected_at.getMonthOfYear() - 1; // Need to subtract 1 here.
int day = inspected_at.getDayOfMonth();
int hour = inspected_at.getHourOfDay();
int minutes = inspected_at.getMinuteOfHour();
dp.updateDate(year, month, day);
tp.setCurrentHour(hour);
tp.setCurrentMinute(minutes);
Hope that helps.
JP
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.