Android format date to MM-DD-YYYY from Datepicker
Asked Answered
S

11

27

I have a datepicker. My app is pushing a notification. I want to display the date in 01-07-2013 MM-dd-yyyy format. Please check my code below:

 //---Button view---
    Button btnOpen = ( Button ) findViewById( R.id.btEventDone );
    btnOpen.setOnClickListener( new View.OnClickListener() {

        public void onClick(View v) {  

            String strT = title.getText().toString();
            String strDes = description.getText().toString();

            // check if user did not input anything
            if( strT.isEmpty() || strDes.isEmpty() ){

                Toast.makeText( getBaseContext(), "You have blank fields!", Toast.LENGTH_SHORT ).show();

            }
            else{

            //---use the AlarmManager to trigger an alarm---
            AlarmManager alarmManager = ( AlarmManager ) getSystemService( ALARM_SERVICE );                 

            //---get current date and time---
            Calendar calendar = Calendar.getInstance();       

            //---sets the time for the alarm to trigger---
            calendar.set( Calendar.YEAR, date.getYear() );
            calendar.set( Calendar.MONTH, date.getMonth() );
            calendar.set( Calendar.DAY_OF_MONTH, date.getDayOfMonth() );                 
            calendar.set( Calendar.HOUR_OF_DAY, time.getCurrentHour() );
            calendar.set( Calendar.MINUTE, time.getCurrentMinute() );
            calendar.set( Calendar.SECOND, 0 );

            //---PendingIntent to launch activity when the alarm triggers---                    
            Intent i = new Intent( CalendarEvent.this, DisplayNotification.class );

            year = calendar.get( Calendar.YEAR );
            month = calendar.get( Calendar.MONTH );
            day = calendar.get( Calendar.DAY_OF_MONTH );

            hour = calendar.get( Calendar.HOUR );
            minute = calendar.get( Calendar.MINUTE );

            Date d = new Date(year, month, day);
            SimpleDateFormat dateFormatter = new SimpleDateFormat(
                            "MM-dd-yyyy");
            String strDate = dateFormatter.format(d);

            String strTitle = title.getText().toString();
            String strDescription = description.getText().toString();
            strDate = String.valueOf( month ) + "-" + String.valueOf( day ) + "-" + String.valueOf( year );

            StringBuilder sb = new StringBuilder();
            if(hour>=12){                      
              sb.append(hour-12).append( ":" ).append(minute).append(" PM");
            }else{
              sb.append(hour).append( ":" ).append(minute).append(" AM");
            }
            String strTime = sb.toString();


            //---assign an ID of 1---
            i.putExtra( "NotifID", notifID ); 
            i.putExtra( "Title", strTitle );
            i.putExtra( "Description", strDescription );
            i.putExtra( "Date", strDate  );
            i.putExtra( "Time", strTime );

            PendingIntent displayIntent = PendingIntent.getActivity(
                getBaseContext(), notifID, i, 0 );               


            //---sets the alarm to trigger---
            alarmManager.set( AlarmManager.RTC_WAKEUP, 
                calendar.getTimeInMillis(), displayIntent );
            finish();
        }

        }
    }); 

}

AlarmDetails:

@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.alarmdetails);  

    //---look up the notification manager service---
    NotificationManager nm = ( NotificationManager ) 
        getSystemService( NOTIFICATION_SERVICE );

    title = ( EditText ) findViewById ( R.id.etDetailTitle );
    description = ( EditText ) findViewById ( R.id.etDetailDescription );
    date = ( EditText ) findViewById ( R.id.etDetailDate );
    time = ( EditText ) findViewById ( R.id.etDetailTime );
    done = ( Button ) findViewById ( R.id.btnAlarmDone );

    done.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            finish();
        }
    });

    //---cancel the notification---
    nm.cancel( getIntent().getExtras().getInt( "NotifID" ) ); 


    String strTitle = getIntent().getExtras().getString( "Title" );
    String strDescription = getIntent().getExtras().getString( "Description" );
    strDate = getIntent().getExtras().getString( "Date" );
    String strTime = getIntent().getExtras().getString( "Time" );
    title.setText( strTitle );
    description.setText( strDescription );
    date.setText( strDate );
    time.setText( strTime );


}

DisplayNotification:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

//---get the notification ID for the notification; 
// passed in by the NotifyActivity---
int notifID = getIntent().getExtras().getInt( "NotifID" );
String strTitle = getIntent().getExtras().getString( "Title" );
String strDescription = getIntent().getExtras().getString( "Description" );
String strDate = getIntent().getExtras().getString( "Date" );
String strTime = getIntent().getExtras().getString( "Time" );

//---PendingIntent to launch activity if the user selects 
// the notification---
Intent i = new Intent( DisplayNotification.this, AlarmDetails.class );
i.putExtra( "NotifID", notifID );  
i.putExtra( "Title", strTitle );
i.putExtra( "Description", strDescription );
i.putExtra( "Date", strDate );
i.putExtra( "Time", strTime );

PendingIntent detailsIntent = 
    PendingIntent.getActivity(this, 0, i, 0);

NotificationManager nm = ( NotificationManager )
    getSystemService( NOTIFICATION_SERVICE );
Notification notif = new Notification(
    R.drawable.ic_launcher, 
    "iHealthFirst: Notification!",
    System.currentTimeMillis() );

CharSequence from = "iHealthFirst - New Notification";
CharSequence message = "This is your alert, click to view";        
notif.setLatestEventInfo(this, from, message, detailsIntent);
notif.flags = Notification.FLAG_INSISTENT;
notif.defaults |= Notification.DEFAULT_SOUND;

//---100ms delay, vibrate for 250ms, pause for 100 ms and
// then vibrate for 500ms---
notif.vibrate = new long[] { 100, 250, 100, 500};        
nm.notify( notifID, notif );

//---destroy the activity---
finish();
}

My current app only display in this format M-d-yyyy. I have read that we should use SimpleDateFormat, but I don't know how to use it in my app. Can anyone help? Thanks.

Smokeless answered 7/1, 2013 at 6:27 Comment(0)
A
20

Check this:

date format change in datepicker and calendar

   year = calendar.get(Calendar.YEAR);
   month = calendar.get(Calendar.MONTH);
   day = calendar.get(Calendar.DAY_OF_MONTH);

    if(month < 10){

        month = "0" + month;
    }
    if(day < 10){

        day  = "0" + day ;
    }
    searchText.setText(day + "-" + month + "-" + year);
Achernar answered 7/1, 2013 at 6:36 Comment(0)
T
35

try this

int year = mDatePicker.getYear();
int month = mDatePicker.getMonth();
int day = mDatePicker.getDayOfMonth();

Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);

SimpleDateFormat format = new SimpleDateFormat("MM-dd-yyyy");
String strDate = format.format(calendar.getTime());
Thanos answered 30/9, 2014 at 9:37 Comment(1)
This solution is much elegant.Hershey
A
20

Check this:

date format change in datepicker and calendar

   year = calendar.get(Calendar.YEAR);
   month = calendar.get(Calendar.MONTH);
   day = calendar.get(Calendar.DAY_OF_MONTH);

    if(month < 10){

        month = "0" + month;
    }
    if(day < 10){

        day  = "0" + day ;
    }
    searchText.setText(day + "-" + month + "-" + year);
Achernar answered 7/1, 2013 at 6:36 Comment(0)
A
5

A simple way to do this might be to simply collect the data and then use String.format:

    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH) + 1;
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    String dateString = String.format("%02d-%02d-%d", month, day, year);
    ((TextView) m_view.findViewById(R.id.dob)).setText(dateString);
Armond answered 24/2, 2018 at 1:25 Comment(0)
M
4

You can add this code:

Date d = new Date(year, month, day);
SimpleDateFormat dateFormatter = new SimpleDateFormat(
                "MM-dd-yyyy hh:mm");
strDate = dateFormatter.format(d);

after

year = calendar.get( Calendar.YEAR );
month = calendar.get( Calendar.MONTH );
day = calendar.get( Calendar.DAY_OF_MONTH );

hour = calendar.get( Calendar.HOUR );
minute = calendar.get( Calendar.MINUTE );

So your strDate will be in format you want (MM-dd-yyyy)

Magnetize answered 7/1, 2013 at 6:32 Comment(10)
maybe you mean d in strDate = dateFormatter.format(date); not date? thnksSmokeless
@bEtTyBarnes, Yes, it will be 'd' instead of variable 'date'. I am editingJadwigajae
@bEtTyBarnes, Can you please edit your question with new code? Because this code works perfectly in my appsJadwigajae
Hi i've added my 2 classes. Thanks.Smokeless
@bEtTyBarnes, you have put the code at wrong place. Place it before you pass the intent from class DisplayNotification.Jadwigajae
Yeah I've done that, I deleted the code from alarmdetails. I put it in the main activity class but it still displays the same.Smokeless
@bEtTyBarnes, After placing that code your value for strDate is being overridden as you have not removed this line: "strDate = String.valueOf( month ) + "-" + String.valueOf( day ) + "-" + String.valueOf( year );". Remove it and check. I thnk problem should be solvedJadwigajae
@bEtTyBarnes, Do one thing. Put a debugging point on String strDate = dateFormatter.format(d); and check the value of strDate at that time. So we can get an idea about the source of problemJadwigajae
let us continue this discussion in chatSmokeless
The value of date is 3913.Smokeless
M
2

just use this code..

 date.setOnClickListener(new OnClickListener() 
        {

            public void onClick(View v) 
            {
                DatePickerDialog dateDlg = new DatePickerDialog(New_Quote_Activity.this, new DatePickerDialog.OnDateSetListener() 
                {

                         public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth) 
                         {
                                CharSequence strDate = null;
                                    Time chosenDate = new Time();        
                                    chosenDate.set(dayOfMonth, monthOfYear, year);
                                    long dtDob = chosenDate.toMillis(true);

                                    strDate = DateFormat.format("MM/dd/yyyy", dtDob);

                                    txtDate.setText(strDate);
                        }}, year,month,day);

                      dateDlg.show();
               }
        });
Mack answered 8/1, 2013 at 7:5 Comment(0)
B
0
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

 public class MainClass {
     public static void main(String[] args) {
     String pattern = "MM-dd-yyyy";
     SimpleDateFormat format = new SimpleDateFormat(pattern);
   try {
      Date date = format.parse("01-07-2013");
      System.out.println(date);
   } catch (ParseException e) {
     e.printStackTrace();
    }

    System.out.println(format.format(new Date()));
 }
}

Hope its helpful.

You can also refer to the documentation.

Bellew answered 7/1, 2013 at 6:33 Comment(0)
G
0

I want to display the date in 01-07-2013 MM-dd-yyyy format.

yes you can Do this by Below Steps.

Step 1: you First have to Convert your String to Particular Date Format

Step 2: Using SimpleDateFormat Convert your Date to MM-dd-yyyy format

Step 3: Convert to String and Use it.

you can User Below Code for this.

 public class DateFormat {

   public static void main(String[] args) {
    // Put here what your are getting as String
    String mytime="Jan 7, 2013"; 
    SimpleDateFormat dateFormat = new SimpleDateFormat(
            "MMM dd, yyyy"); //Step1: Convert yout String to perticular Date Formate according to your Date String your are getting
    Date myDate = null;
    try {
        myDate = dateFormat.parse(mytime);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    //Step2
    SimpleDateFormat timeFormat = new SimpleDateFormat("MM-dd-yyyy");
    String finalDate = timeFormat.format(myDate); 
    //Step3: Here you will get your Final Date. Set your String now to textview.
       }
}

Hope it will help you.

Geelong answered 7/1, 2013 at 6:34 Comment(0)
C
0

Try out this way:

private int m_month, m_year, m_day;
 SimpleDateFormat dateParser = new SimpleDateFormat("MM-dd-yyyy",
            Locale.ENGLISH);
 m_month = m_calendar.get(Calendar.MONTH) + 1;
 m_year = m_calendar.get(Calendar.YEAR);
 m_day = m_calendar.get(Calendar.DAY_OF_MONTH);
 //for the datepicker listener.
 m_calendar.set(Calendar.YEAR, p_year);
 m_calendar.set(Calendar.MONTH, p_monthOfYear);
 m_calendar.set(Calendar.DAY_OF_MONTH, p_dayOfMonth);
 String m_sDate = dateParser.format(m_calendar.getTime()).toString();
Calamitous answered 7/1, 2013 at 6:35 Comment(0)
D
0

I tried following in my project. It might help you. Ask if you have any query.

try{
    SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
    Date originalDate = new Date();   //it will give today's date.
    String dateString = sdf.format(originalDate);
    Date formattedDate = sdf.parse(dateString);

}catch(Exception e){
    e.printStackTrace();
}
Drugge answered 7/1, 2013 at 6:36 Comment(0)
C
0

Try this:

        CharSequence formatted = DateFormat.format("MM/dd/yyyy", mDueDate);
        mDueDateView.setText(formatted);
Cowell answered 2/12, 2016 at 14:23 Comment(0)
S
0

Try doing it with if else statement may help :

//date picker code
date_c_input.setInputType(InputType.TYPE_NULL);
date_c_input.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { 
    
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);

// date picker dialog
picker = new DatePickerDialog(AddActivity_C.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
String month_s="00";
String day_s="00";
monthOfYear= monthOfYear+ 1;
if(dayOfMonth < 10){

        day_s  = "0" + dayOfMonth ;
    }else {
        day_s=Integer.toString(dayOfMonth);
    }
if(monthOfYear < 10){

        month_s = "0" + monthOfYear;
    }else{
        month_s=Integer.toString(monthOfYear);
    }
date_c_input.setText(year+"-"+month_s+"-"+day_s);   
}
}, year, month, day);
picker.show();
}
}); 
//end of date code
Subterfuge answered 14/4, 2023 at 16:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.