How to show native Islamic(hijri) Calendar? - android

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");

Related

How to get total number of months from a specific Date?

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();
}

comparing date and time in date picker

I have a date picker dialog, using which user can select a date. Conditions are :
Date must not be greater than today (system date)
Date must not be older than 3 months
I have done the first bit but I am not sure how to compare two dates to check if it is older than 3 months.
in the code : checkInYear, checkInMonth and checkInDay is what user selected and year, month, day is the system date.
Could you please suggest how to compare two dates to check if it is greater than 3 months.
Your help is much appreciated.
#Override
public void onDateChanged(DatePicker view, int selectedYear,
int selectedMonthOfYear, int selectedDayOfMonth) {
setCurrentDateOnView();
int checkInYear = selectedYear;
int checkInMonth = selectedMonthOfYear;
int checkInDay = selectedDayOfMonth;
if (checkInYear > year || checkInYear < year) {
view.updateDate(year, month, day);
}
if (checkInMonth > month && checkInYear == year) {
view.updateDate(year, month, day);
}
if (checkInDay > day && checkInYear == year
&& checkInMonth == month) {
view.updateDate(year, month, day);
}
}
};
Thank you very much
Just use according to your need.
String sDate = "05-10-2012"; // suppose you create this type of date as string then
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(sDate);
Calendar c = Calendar.getInstance();
c.getTime().compareTo(date);
it depending on your string or how you can get? you can get all individually from datepicker then directly set in calendar instance
Calendar my = Calendar.getInstance();
my.set(year, month, day);
now compare
my.compareTo(Calendar.getInstance());
and for less then 3 months you can use something like ..
Date referenceDate = new Date();
Calendar c = Calendar.getInstance();
c.setTime(referenceDate);
c.add(Calendar.MONTH, -3);
return c.getTime();

save current date into database

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.

Get Day of week and Month name from DatePicker

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

Android CalendarView: How do I get the date in correct format?

The past few days I've been searching for ways to get a 'readable' date out of my calendarview from android 4.0. I can't manage to find a solution or example that suits my problem. I did get it in miliseconds but not in a date format.
My problem is: I have a calendarview and I want the selected date by the user, shown in logcat in a dateformat yy-mm-dd.
I was used to the datepicker from android 2.2 and I'm not familiar with calendarview and can't find much about it either. Does anyone know a solution for this?
Okay so here is how to do this. When you fire your calendarview activity or a calendarview inside your activity it sets the date to the current date(meaning today). To get this current date just use the Calendar object provided by the java api to get this date example below:
Calendar date = Calendar.getInstance();
// for your date format use
SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
// set a string to format your current date
String curDate = sdf.format(date.getTime());
// print the date in your log cat
Log.d("CUR_DATE", curDate);
to get a date changed you must do this
CalendarView myCalendar = (CalendarView) findViewById(R.id.myCalenderid);
myCalendar.setOnDateChangeListener(myCalendarListener);
OnDateChangeListener myCalendarListener = new OnDateChangeListener(){
public void onSelectedDayChange(CalendarView view, int year, int month, int day){
// add one because month starts at 0
month = month + 1;
// output to log cat **not sure how to format year to two places here**
String newDate = year+"-"+month+"-"+day;
Log.d("NEW_DATE", newDate);
}
}
kandroidj's answer helps to create date, but not date of correct format.
So to format selected date:
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
#Override
public void onSelectedDayChange(CalendarView view, int year, int month,
int dayOfMonth) {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, dayOfMonth);
String sDate = sdf.format(calendar.getTime());
Log.d(TAG, "sDate formatted: " + sDate);
}
});
You should use SimpleDateFormat
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String selectedDate = sdf.format(new Date(calendar.getDate()));
long date = calenderView.getDate();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(date);
int Year = calendar.get(Calendar.YEAR);
int Month = calendar.get(Calendar.MONTH);
int Day = calendar.get(Calendar.DAY_OF_MONTH);
//customize According to Your requirement
String finalDate=Year+"/"+Month+"/"+Day;

Categories

Resources