The date from DateRangePicker displays as: "yyyy-M-d".
But I want it to display the date as: "yyyy-MM-dd".
I have tried out the following code:
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth, int yearEnd, int monthOfYearEnd, int dayOfMonthEnd) {
String selection1 = year + "-" + (monthOfYear+1) + "-" + dayOfMonth;
String selection2 = yearEnd + "-" + (monthOfYearEnd+1) + "-" + dayOfMonthEnd;
Long firstDateSelection = Long.parseLong(selection1);
Long secondDateSelection = Long.parseLong(selection2);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = new Date(firstDateSelection);
Date endDate = new Date(secondDateSelection);
formatter.format(startDate); formatter.format(endDate);
But I get NumberFromatException when I run it at "Long firstDateSelection = Long.parseLong(selection1)"?
Help is much appreciated :)
Thanks!
You are getting NumberFormatException because "1234-12-23" is not a valid Long number and you are trying to convert it to a Long here:
Long firstDateSelection = Long.parseLong(selection1);
Since you already have the numbers for day, month and year you can simply format it(no need for SimpleDateFormat):
String dateString = String.format("%1$04d-%2$02d-%3$02d", year, monthOfYear, dayOfMonth);
If you check Javadoc about parseLong(string)
Throws
NumberFormatException
if the string does not contain a parsable long.
As you can see a string with "-" is not a long number and it throws that exception.
If you want to do it correctly you have to create a Calendar, add it the values you are passing by parameters (year, monthOfYear...) with set(...) and then make getTime() to get Date object.
Don't create a Date object directly (new Date...) because its methods setHour, etc. are deprecated.
Once you have that, you will be able to do .format(dateObject).
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 want show date into my application, and i receive this data from server with below json :
"date": "2016-08-01 19:55:16"
and i set into textview with below code :
((DataViewHolder) holder).main_dateTime.setText(Html.fromHtml(mDateSet.get(position).getDate()));
I want convert this date to jalali/shamsi . but i don't know how to convert this date and set into textview !
Can you help me for this issue?
Use this https://github.com/amirmehdizadeh/JalaliCalendar to get the Jalali date
first get the year, month and day from your date like
String date = "2016-08-01 19:55:16";
String[] parts = date.split(" ");
String datePart = parts[0];
String timePart = parts[1];
int year;
int month;
int day;
String[] dateParts = datePart.split("-");
year = Integer.parseInt( dateParts[0]);
month = Integer.parseInt( dateParts[1]);
day = Integer.parseInt( dateParts[2]);
then create the Object to pass to that library
JalaliCalendar.YearMonthDate georgianDate = new JalaliCalendar.YearMonthDate(year,month,day);
and then call its method that convert from Georgian date to Jalali Date
JalaliCalendar.YearMonthDate JalaliDate = JalaliCalendar.gregorianToJalali(georgianDate);
And Finally append the date with time to show in text view
String jalaliDateTime = JalaliDate.toString() + " " + timePart;
textView.setText(jalaliDateTime);
//When user clicks "other".
public void setDate(View view) {
DateTime dateTime=new DateTime();
new DatePickerDialog(CreateEventActivity.this, listener, dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfWeek()).show();
}
DatePickerDialog.OnDateSetListener listener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
DateTime eventDate = new DateTime();
eventDate.withYear(year);
eventDate.withMonthOfYear(monthOfYear + 1);
eventDate.withDayOfMonth(dayOfMonth);
time = eventDate;
Context appContext = getApplicationContext();
Toast.makeText(appContext, dayOfMonth + "/" + (monthOfYear + 1) + "/" + year + "," +eventDate.dayOfWeek().getAsText(), Toast.LENGTH_LONG).show();
dateTxt.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
dayTxt.setText(eventDate.dayOfWeek().getAsText());
otherButton.setBackgroundColor(Color.parseColor("#77B3FC"));
todayButton.setBackgroundColor(Color.parseColor("#DBDBDB"));
tomorrowButton.setBackgroundColor(Color.parseColor("#DBDBDB"));
}
};
I have a problem with this part: eventDate.dayOfWeek().getAsText()
It shows the wrong day of the week, but the date in numbers is fine.
(Just started using Joda-Time so I'm not sure about it...)
EDIT:
The date in numbers like: 23.7.16 is printed correctly, But I want it to show which day is it in the week, like "Monday"... I've noticed it always writes today's name. In the toast and in the text view...
For example, for couple of different dates it will show:
23.6.16, Friday|
15.7.16, Friday|
30.8.17, Friday
the others data are right because you are using the data of the DataPicker and not of the JodaTime, may have some error in your construction try:
DateTime eventDate = new DateTime(year,monthOfYear+1,dayOfMonth,0,0,0);
the 0,0,0 are hours, minutes and seconds, remove the 3 lines :
eventDate.withYear(year);
eventDate.withMonthOfYear(monthOfYear + 1);
eventDate.withDayOfMonth(dayOfMonth);
I have been struggling with this for a while.
Is there a method to ALWAYS display the date format in YYYY/MM/DD in a DatePicker widget regardless of user specific locales?
I have been searching the web for the whole day but I can only find how to get the date/time and convert it to other formats but not how to actually get the cursed widget to display a different time format.
The only related answer that I can find on stackoverflow is this. Surely there has to be an easier way than to brute force the API.
To clarify my context and usage: I'm using my DatePicker in a Fragment(NOT DialogFragment extending a DatePickerDialog).
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
int month = monthOfYear + 1;
String formattedMonth = "" + month;
String formattedDayOfMonth = "" + dayOfMonth;
if(month < 10){
formattedMonth = "0" + month;
}
if(dayOfMonth < 10){
formattedDayOfMonth = "0" + dayOfMonth;
}
searchText.setText(formattedDayOfMonth + "/" + formattedMonth + "/" + year);
}
I'd like to get day, month and year values for save to db. These are my codes:
Declaretions:
private TextView tv_purchase_date;
private Button mPickDate;
private int mYear;
private int mMonth;
private int mDay;
OnClickListener listener_show_dlg = null;
OnDateSetListener listener_mdate_display = null;
Event Code:
listener_show_dlg = new OnClickListener() {
public void onClick(View v) {
Calendar cal=Calendar.getInstance();
DatePickerDialog datePickDlg = new DatePickerDialog(
ItemsAddActivity.this,
listener_mdate_display,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
);
datePickDlg.show();
};
};
listener_mdate_display = new OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
mMonth = month;
mYear = year;
mDay = dayofMonth;
tv_purchase_date.setText(dayOfMonth + "/" + monthOfYear + "/" + year);
}
};
}
I try to store mMonth, mYear and mDay values in db. What is the best store type? as integer or as string??
I store in the DB one number that represents the date. It is the number of seconds that have passed since the beginning of the modern era (Jan 1, 1970.) From the Date Picker, you can get the M D Y values like this:
datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int yearOfYear,
int monthOfYear, int dayOfMonth) {
// the user has picked these values
year = yearOfYear;
month = monthOfYear;
day = dayOfMonth;
Then, I turn these into a single Date object like this.
Calendar cal = new GregorianCalendar(year, month, day);
Date dateOfGames = cal.getTime();
DateFormat df = DateFormat.getDateInstance(DateFormat.LONG);
String cs = df.format(dateOfGames);
changeDateButton.setText(cs); // update the interface
}
};
before I put it in the DB, I turn it into a numebr of seconds like this:
long seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
....
when I take that single number of seconds out of the DB, and want it to be a Date object again, I do this:
date = new Date(seconds * 1000); // converting seconds to a Date object
You can use a DateFormat object to display the date object how you like to see it.
I know this is awkward. Since SQLite doesn't allow you to store a Date, the answer is going to be awkward. Perhaps there is a cleaner way than this, and others will recommned something. :)
I struggled with this issue for a while. I don't konw of anything better than this.
I stored the date in the DB as a single long int. It is pretty easy to convert your Date to the number of seconds since the epoch (Jan 1, 1970), and it is also easy to convert the number of seconds into a Date object.
You need to be careful with seconds and milliseconds.
date = new Date(seconds * 1000); // converting seconds to a Date
seconds = date.getTime() / 1000; // this is the date in seconds since the start of the epoch
// Use Greg calendar to get a Date object from day, month, year
Date dateOfGames = new GregorianCalendar(year, month, day).getTime();
Does that help at all?
I created sqllite table with this sql string:
create table items (id INTEGER PRIMARY KEY AUTOINCREMENT, pdate DATE)
I writed some methods to convert date:
public String date_to_str(Date date) {
String pattern = "dd.MM.yyyy";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
Log.d(_watcher_name, "date_to_str" + dateFormat.format(date));
return dateFormat.format(date);
}
public Date mdy_to_date (int day, int month, int year) {
Calendar cal = new GregorianCalendar(year, month, day);
return cal.getTime();
}