This question already has answers here:
How to format date and time in Android?
(26 answers)
Closed 5 years ago.
I am building an IOS and Android version and in my IOS, the date is formatted this way "June 23, 2017 at 8:58 AM".
In Android I am getting the date in numbers and then I assign them like this:
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
date_time = dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
timePicker();
}
and here is the timePicker() method:
private void timePicker(){
// Get Current Time
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
mHour = hourOfDay;
mMinute = minute;
et_show_date_time.setText(date_time+" "+hourOfDay + ":" + minute);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
which result to something like this "27-6-2017 16:55"
How can I formatted similar to the IOS version?
You can do this by SimpleDateFormat
Date currentTime = Calendar.getInstance().getTime();
String newFormat="";
try
{
SimpleDateFormat form = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
newFormat = form.format(currentTime);
tvAppliedDate.setText(newFormat);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(this, "parse error", Toast.LENGTH_SHORT).show();
}
Related
I have Calendar value which is from Date Picker and I want to convert this value to String format "yyyy-MM-dd"
This is my Date Picker code. I save the selected values to startYear, startMonth and startDay.
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
and then I tried to convert these values to String in this way. But the log result is 0002-12-31 not what I selected from Date Picker.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Never use Calendar. That terrible class was supplanted years ago by the modern java.time classes.
LocalDate
Instead, use LocalDate for a date-only value with no time-of-day and no offset or time zone.
LocalDate x = LocalDate.now() ;
String output = x.toString() ;
Build from parts.
LocalDate x = LocalDate.of( y , m , d ) ;
Get parts.
int y = x.getYear() ;
int m = x.getMonthValue() ;
int d = x.getDayOfMonth() ;
If your code goes like this; the log shows the date value before picking any dates. So you see the value for year: 0, month: 0 and day:0 (which is shown as 0002-12-31). (Note that the code inside onDateSet() method runs asynchronously, when the user picks a date.)
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
// startYear, startMonth, startDay are not initialized yet and equal 0.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
Instead; if you try to convert your Date to String "after the values are set" (Shown below) .You can see it will be correctly converted.
int startYear, startMonth, startDay;
Calendar today = GregorianCalendar.getInstance();
ipDcEventStartDay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
DatePickerDialog dpd = new DatePickerDialog(DoubleCheckEventActivity.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
startYear = year;
startMonth = month;
startDay = dayOfMonth;
ipDcEventStartDay.setText(startYear+ "-" + (startMonth+1) + "-" + startDay);
ipDcEventStartDay.setTextColor(Color.parseColor("#000000"));
//************************************************************
//Now we have the picked values.
Calendar start = Calendar.getInstance();
start.set(startYear, startMonth, startDay);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = start.getTime(); // Convert to Date
String strStartDate = sdf.format(startDate); // Convert to String
Log.d("start", strStartDate); // this result is 0002-12-31
//************************************************************
}
}, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DATE));
dpd.show();
}
});
Let's see the simple code to convert Date to String
Basic
Date date = Calendar.getInstance().getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
String strDate = dateFormat.format(date);
System.out.println("Converted String: " + strDate);
Advanced
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
}
I have created a DatePicker within my app. But the problem I am trying to overcome is how to take the picked date and store it in my database:
In my DB, the date field is set to TEXT
private int mYear, mMonth, mDay, mHour, mMinute;
#Override
public void onClick(View v) {
final Calendar calendar = Calendar.getInstance();
//Get the date
if (v == buttonDatePicker) {
mYear = calendar.get(Calendar.YEAR);
mMonth = calendar.get(Calendar.MONTH);
mDay = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this,
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
etDate.setText(dayOfMonth + "-" + month + "-" + year);
mYear = year;
mMonth = month;
mDay = dayOfMonth;
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
//Get the time
if (v == buttonTimePicker) {
mHour = calendar.get(Calendar.HOUR_OF_DAY);
mMinute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
etTime.setText(hourOfDay + ":" + minute);
mHour = hourOfDay;
mMinute = minute;
}
}, mHour, mMinute, true);
timePickerDialog.show();
}
}
I tried to convert the picked Year etc from int to String but it does not seem to like it when I tried to cast it.
How I am trying to store it in my DB :
typedUpSmsMessage = smsMessage.getText().toString();
ContentValues cv = new ContentValues();
cv.put("textMessage", typedUpSmsMessage);
cv.put("dateToSendText",mYear + mMonth + mDay);
cv.put("gameID", gameID);
automateGameDB.insert("automateGames", null, cv);
But ofcourse since the date is in int, it just adds the numbers.
Need to convert them into a string, or a date format? (yyyy-mm-dd hh-mm-ss)?
Thanks
Since the field is Text you should use cv.put("dateToSendText", year + "-" + month + "-" + dayOfMonth) with 4 digit year and 2 digit month and dayOfMonth, because it is comparable and sortable.
Insert your date in database like
cv.put("dateToSendText",dayOfMonth + "-" + month + "-" + year)
or
cv.put("dateToSendText",etTime.gettext().tostring());
Really don't understand your requirement.
Will this code
String string = Integer.toString(int); or String.valueOf(int) or simply string+""
solve your problem?
I advise you to store Date as a timestamp in your database :
Calendar calendar = Calendar.getInstance()
calendar.set(year, month, day, hour, minute, second)
Long timestamp = calendar.getTimeInMillis() // Save timestamp in database
Use
inputDate = mYear +"-"+ mMonth +"-"+ mDay;
SimpleDateFormat src = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
SimpleDateFormat dest = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.US);
Date date = null;
try {
date = src.parse(inputDate);
} catch (ParseException e) {
Log.d("Exception",e.getMessage());
}
String formattedDate = dest.format(date);
You can change dest Dateformat as u want...
Use 'TEXT' datatype in sqlite to store this date field
I have 2 android datepickers and I want to get the dayOfWeek in each date picker but I get only the initial calendar day even if I change it. How to set the clickListener? I would like to get the day of the week in dayOfWeek and dayOfWeek1 variables.
dpTake=(DatePicker) rootView.findViewById(R.id.dpTake);
dpDelivery=(DatePicker) rootView.findViewById(R.id.dpDelivery);
Date dt = new Date();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
dpDelivery.updateDate(c.YEAR, c.MONTH, c.DAY_OF_MONTH);
c.add(Calendar.DATE, 1);
dt = c.getTime();
dpTake.setMinDate(dt.getTime());
CalendarView cv = dpTake.getCalendarView();
long current = cv.getDate();
cv.setDate(cv.getMaxDate(), false, true);
cv.setDate(current, false, true);
c.add(Calendar.DATE, 2);
dt = c.getTime();
dpDelivery.setMinDate(dt.getTime());
CalendarView cvDelivery = dpDelivery.getCalendarView();
current = cvDelivery.getDate();
cvDelivery.setDate(cv.getMaxDate(), false, true);
cvDelivery.setDate(current, false, true);
dayOfWeek1 = c.get(Calendar.DAY_OF_WEEK);
Try this code
DatePickerDialog dpd = DatePickerDialog.newInstance(
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, monthOfYear);
calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
}
},
calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH)
);
dpd.setAccentColor(Color.parseColor("#029789"));
dpd.setMinDate(Calendar.getInstance());
dpd.show(getActivity().getFragmentManager(), "Datepickerdialog");
I getting two date from calendars.It writing into a string builder.I want to getting difference between two date also I want to keep the number of days remaining between times,except weekends.
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
public void onDateSet(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
if (cur == DATE_DIALOG_ID) {
// set selected date into textview
permitDate = new StringBuilder().append(day).append(".").append(month + 1).append(".").append(year).append(" ").toString();
tvDisplayDate.setText("Date : " + permitDate);
} else {
startDate = new StringBuilder().append(day).append(".").append(month + 1) .append(".").append(year).append(" ").toString();
tvDisplayDate2.setText("Date : " + startDate);
}
}
};
Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,25);
thatDay.set(Calendar.MONTH,7); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 1985);
Calendar today = Calendar.getInstance();
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);
To Parse the date from a string, you could use
String strThatDay = "1985/08/25";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date d = null;
try {
d = formatter.parse(strThatDay);//catch exception
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Calendar thatDay = Calendar.getInstance();
thatDay.setTime(d); //rest is the same....
Use JodaTime library to find the difference between dates.
For more information follow the instructions Use Joda Time.
I want interval date. Whatever user enter date from date picker and from this date I want to get after one month date Suppose 1 Aug 2014 -> Output will be 1 September 2014.Can someone help me .Thanks to appreciate.
Hare is my Activity code
{
// Get current date by calender
final Calendar c = Calendar.getInstance();
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
// Month is 0 based, just add 1
etReplacementDate.setText(new StringBuilder()
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
etReplacementDate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_OF_REPLACEMENT);
}
});
String fixedDate = etReplacementDate.getText().toString().trim();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
Date convertedDate = new Date();
try
{
convertedDate = dateFormat.parse(fixedDate);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Date Consersion = " + convertedDate);
/****************ReplaceMent Date***************************************************/
cal2.add(Calendar.getInstance(convertedDate), 30);
Date date_30dayslater = cal2.getTime();
System.out.println("date_30dayslater : " + date_30dayslater);
/****************Interval Date***************************************************/
String _30daysLater_String = new SimpleDateFormat("yyyy-MM-dd").format(date_30dayslater);
etNextReplanishmentDate.setText(_30daysLater_String);
System.out.println("30 days later: " + _30daysLater_String);
System.out.println("______________________________________");
/****************Before Date***************************************************/
cal2.add(Calendar.DATE, -1);
Date beforDate = cal2.getTime();
String beforDate_String = new SimpleDateFormat("yyyy-MM-dd").format(beforDate);
System.out.println("beforDate_String: " + beforDate_String);
}
#Override
protected Dialog onCreateDialog(int id)
{
switch (id)
{
case DATE_OF_REPLACEMENT:return new DatePickerDialog(this, pickerListenerReplacement, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener pickerListenerReplacement = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
etReplacementDate.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
}
What you want to do is add() one Calendar.MONTH to a date that you've gotten and parsed, etc. so I won't go into that. I'll assume you are handling everything correctly up to the point where you'd like to get the same day, if possible, of the next month.
Part of your problem, as your comment suggests, is Calendar.getInstance() does not have an implementation that takes a Date. But more importantly you don't need it. You have a Date and a Calendar instance and it seems like you're changing c2 anyway so why not use Calendar's setTime() method like this?
// setting c2 with the convertedDate then adding a month
c2.setTime(convertedDate);
c2.add(Calendar.MONTH, 1);
// Simple example
public static void main(String...args) {
Date d = new Date();
Calendar c = Calendar.getInstance();
c.setTime(d);
System.out.println(c.getTime());
c.add(Calendar.MONTH, 1);
System.out.println(c.getTime());
}
try to use this.
Calendar c = Calendar.getInstance();
int month = c.get((Calendar.MONTH));
c.set(Calendar.MONTH, month + 1);
long time = c.getTimeInMillis();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String result = sdf.format(new Date(time1));