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
Related
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 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.
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;
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.