获取时间 year/month/day/hour/minutes 并转换为毫秒,如 java 或 android 中的 getTime()

Get time as year/month/day/hour/minutes and convert to millisecond like getTime() in java or android

我想从用户那里获取时间(使用像 year/month/day/hour/minutes 这样的编辑框)。 我如何将它转换为像 getTime 函数一样的毫秒或像 getTime()/60000 一样转换为分钟?

您可以使用 DatePicker and then use the getters from that to either make a Calendar 对象或以毫秒为单位获取时间。

我在我的项目中使用此功能从 DatePicker 获取 Calendar,您可能还想扩展它以设置小时/分钟:

public static Calendar getCalenderFromDatePicker(DatePicker dp) {
    int day = dp.getDayOfMonth();
    int month = dp.getMonth();
    int year = dp.getYear();

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

获得 Calendar 后,您可以使用 myCalendar.getTimeInMillis(),其中 returns 是自纪元以来的 long 时间(以毫秒为单位)。

考虑 java.util.Calendar class 和以下代码:

Calendar calendar = Calendar.getInstance();

int year = 2015;
int month = 4; // "May", months are counting from 0 to 11
int day = 14;
int hour = 14;
int minutes = 15;
int seconds = 16;

// for more clarity I set year/day/month/hours/minutes/seconds separately
// you can also set them at once via calendar.set(year, month, day);
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, day);

calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, seconds);

long composedDateInMilliseconds = calendar.getTimeInMillis();