【问题标题】:Android format date to MM-DD-YYYY from Datepicker从 Datepicker 将日期格式化为 MM-DD-YYYY
【发布时间】:2012-12-20 21:19:05
【问题描述】:

我有一个日期选择器。我的应用正在推送通知。我想以 01-07-2013 MM-dd-yyyy 格式显示日期。请检查下面的代码:

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

        }
    }); 

}

报警详情:

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


}

显示通知:

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

我当前的应用程序仅以 M-d-yyyy 这种格式显示。我读过我们应该使用 SimpleDateFormat,但我不知道如何在我的应用程序中使用它。任何人都可以帮忙吗?谢谢。

【问题讨论】:

    标签: android datepicker date-format


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 这个解决方案非常优雅。
    【解决方案2】:

    检查一下:

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

    【讨论】:

      【解决方案3】:

      一个简单的方法可能是简单地收集数据,然后使用 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);
      

      【讨论】:

        【解决方案4】:

        您可以添加此代码:

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

        之后

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

        所以你的 strDate 将采用你想要的格式 (MM-dd-yyyy)

        【讨论】:

        • 也许你的意思是 d in strDate = dateFormatter.format(date);不约会?谢谢
        • @bEtTyBarnes,是的,它将是“d”而不是变量“日期”。我正在编辑
        • @bEtTyBarnes,你能用新代码编辑你的问题吗?因为这段代码在我的应用中完美运行
        • 您好,我已经添加了 2 个课程。谢谢。
        • 日期的值为3913。
        【解决方案5】:

        只需使用此代码..

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

        【讨论】:

          【解决方案6】:

          试试这个方法:

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

          【讨论】:

            【解决方案7】:

            我尝试在我的项目中关注。它可能会帮助你。询问您是否有任何疑问。

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

            【讨论】:

              【解决方案8】:
              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()));
               }
              }
              

              希望对您有所帮助。

              你也可以refer to the documentation

              【讨论】:

                【解决方案9】:

                我想以 01-07-2013 MM-dd-yyyy 格式显示日期。

                是的,您可以通过以下步骤执行此操作。

                第 1 步:您首先必须将字符串转换为特定日期格式

                第 2 步:使用 SimpleDateFormat 将您的日期转换为 MM-dd-yyyy 格式

                第 3 步: 转换为字符串并使用它。

                您可以为此使用代码下方的用户。

                 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.
                       }
                }
                

                希望对你有所帮助。

                【讨论】:

                  【解决方案10】:

                  试试这个:

                          CharSequence formatted = DateFormat.format("MM/dd/yyyy", mDueDate);
                          mDueDateView.setText(formatted);
                  

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 1970-01-01
                    • 2013-03-18
                    • 1970-01-01
                    • 1970-01-01
                    • 2015-11-03
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-09-01
                    相关资源
                    最近更新 更多