2016-01-23 99 views
-1

我已經完成了設置日期和時間到我的TextView,現在我想知道「如何將日期和時間轉換爲毫秒時,我選擇和設置從DatePicker和TimePicker到TextView」,幫助我的代碼如何將日期和時間轉換爲毫秒?

我試過代碼,

public class MainActivity extends AppCompatActivity { 
private TextView txtDateSet; 
private TextView txtTimeSet; 
int cDay, cMonth, cYear; 
int tHours, tMinutes; 

@Override 
protected void onCreate (Bundle savedInstanceState) { 
    super.onCreate (savedInstanceState); 
    setContentView (R.layout.activity_main); 

    txtDateSet = (TextView) findViewById (R.id.txt_date_display); 
    txtTimeSet = (TextView) findViewById (R.id.txt_time_display); 

    txtDateSet.setOnClickListener (new View.OnClickListener() { 
     @Override 
     public void onClick (View v) { 
      displayAlertDialog(); 
     } 
    }); 

} 

public void displayAlertDialog() { 

    AlertDialog.Builder builder = new AlertDialog.Builder (this); 
    LayoutInflater inflater = (LayoutInflater) getSystemService (Context.LAYOUT_INFLATER_SERVICE); 
    final View layout = inflater.inflate (R.layout.custom_alert, (ViewGroup) findViewById (R.id.lnt_root)); 
    final DatePicker dateSet = (DatePicker) layout.findViewById (R.id.date_picker); 
    final TimePicker timeSet = (TimePicker) layout.findViewById (R.id.time_picker); 
    final TextView txtOk = (TextView) layout.findViewById (R.id.txt_ok); 

    builder.setView (layout); 
    final AlertDialog alertDialog = builder.create(); 
    alertDialog.setCanceledOnTouchOutside (true); 
    alertDialog.show(); 

    txtOk.setOnClickListener (new View.OnClickListener() { 
     @TargetApi(Build.VERSION_CODES.M) 
     @Override 
     public void onClick (View v) { 
      cDay = dateSet.getDayOfMonth(); 
      cMonth = dateSet.getMonth(); 
      cYear = dateSet.getYear(); 
      tHours = timeSet.getCurrentHour(); 
      tMinutes = timeSet.getCurrentMinute(); 

      Calendar cal = Calendar.getInstance(); 
      cal.set(Calendar.YEAR, cYear); 
      cal.set(Calendar.MONTH, cMonth); 
      cal.set (Calendar.DAY_OF_MONTH, cDay); 
      cal.set (Calendar.HOUR_OF_DAY, tHours); 
      cal.set (Calendar.MINUTE, tMinutes); 

      SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy"); 
      String formatedDate = sdf.format(cal.getTime()); 
      txtDateSet.setText (""+formatedDate); 

      SimpleDateFormat stf = new SimpleDateFormat ("hh:mm aa"); 
      String formatedTime = stf.format (cal.getTime()); 
      txtTimeSet.setText (""+formatedTime); 

      alertDialog.dismiss(); 
     } 
    }); 
}} 
+0

你有什麼問題嗎? –

+0

'cal.getTimeInMillis()' –

+0

想知道如何將日期和時間轉換爲毫秒 – Rahul

回答

0

最簡單的方法可能是使用的SimpleDateFormat,已經適當地設置時區: 設置時區是重要的一點在這裏,因爲否則會解釋是在價值當地時區。

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); 
    format.setTimeZone(TimeZone.getTimeZone("UTC")); 

    Date date = format.parse(text); 
    long millis = date.getTime();