日历timeinmillis返回错误的值

时间:2019-04-18 21:21:49

标签: android unix-timestamp

使用DatePicker,我选择一个日期,我需要日期和时间戳 从所选日期开始:

        Calendar calendar = Calendar.getInstance(Locale.GERMANY);



        final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) {
            calendar.set(Calendar.YEAR,year);
            calendar.set(Calendar.MONTH,monthOfYear);
            calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);
            SimpleDateFormat sdf = new SimpleDateFormat("EEEE");

            Ctag = sdf.format(calendar.getTime()).substring(0,3)+".";
            CdTag = String.format("%02d",dayOfMonth);
            Cmonat = String.format("%02d",monthOfYear+1);
            Cjahr  = Integer.toString(year);
            Cdatum = CdTag+"."+Cmonat+"."+Cjahr;
            Ctimestamp = (int) (long) calendar.getTimeInMillis();

            getDatum.setText(Ctag+","+CdTag+"."+Cmonat+"."+Cjahr);

            Snackbar snackbar = Snackbar.make(cl_main,String.valueOf(Long.valueOf(calendar.getTimeInMillis()).intValue()),3000).setDuration(Snackbar.LENGTH_INDEFINITE);
            snackbar.show();


        }
    };

因此,我设置了选择的日期,并且calendar.getTimeInMillis()我希望从该日期开始添加时间戳。

但是例如我今天选择了18.04.2019它返回843974600 当我在UNIX转换网站上进行转换时,它给了我 以下日期:

GMT: Sunday, 29. September 1996 05:23:20
Your time zone: Sonntag, 29. September 1996 07:23:20 GMT+02:00 DST
Relative: 23 years ago

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此代码,它应该可以工作:

 calendar.set(Calendar.YEAR,year);
 calendar.set(Calendar.MONTH,monthOfYear);
 calendar.set(Calendar.DAY_OF_MONTH,dayOfMonth);

 Long timeinmilli = calendar.getTimeInMillis(); //will give tou time in ms

 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //format of the date, choose what you want 

 Date resultdate = new Date(timeinmilli); //create an object date associated to the time in ms

 String date = DateFormat.format(resultdate).toString(); //convert the date into a string with the format you choose