gpt4 book ai didi

java - 从 DatePicker 和 TimePicker 获取时间戳

转载 作者:行者123 更新时间:2023-12-01 19:42:19 25 4
gpt4 key购买 nike

我有一个应用程序,用户在其中使用 DatePicker 和 TimePicker 设置日期和时间。我正在尝试将信息保存为时间戳。我目前正在根据用户选择的日期获取时间戳(请参阅下面的代码):

                Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
final Calendar c = cal.getInstance();
int mYear = c.get(Calendar.YEAR); // current year
int mMonth = c.get(Calendar.MONTH); // current month
int mDay = c.get(Calendar.DAY_OF_MONTH); // current day
// date picker dialog
DatePickerDialog datePickerDialog = new DatePickerDialog(AddEventActivity.this,
new DatePickerDialog.OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// set day of month , month and year value in the edit text
txtDate.setText(dayOfMonth + "/"
+ (monthOfYear + 1) + "/" + year);
c.set(year, monthOfYear, dayOfMonth);
timestamp = c.getTimeInMillis();
}

这工作正常,但由于我没有给出时间,它将时间设置为我创建项目的时间。例如,假设我在 27/4/2019 19:00 设置了一个事件,并在 13:30 保存,则记录的时间戳为 27/4/2019 13:30。

我的 TimePicker 的代码如下:

        txtTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);

TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(AddEventActivity.this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
//adding extra 0 to the front of 1 digit hours and minutes so format is consistent.
String hourFormat = String.format("%02d", selectedHour);
String minFormat = String.format("%02d", selectedMinute);
txtTime.setText(hourFormat + ":" + minFormat);
}
}, hour, minute, true);
mTimePicker.show();
}
});

有没有办法结合所选的日期和时间来创建准确的时间戳?

最佳答案

有一个类级别的日历实例,让我们按照之前的方式实例化它:

Calendar combinedCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

因此,当您选择日期时,请按如下方式设置值:

combinedCal.set(year, monthOfYear, dayOfMonth);

当您选择时间时,只需将选定的小时和分钟设置为同一实例即可:

combinedCal.set(Calendar.HOUR_OF_DAY, selectedHour);
combinedCal.set(Calendar.MINUTE, selectedMinute);

关于java - 从 DatePicker 和 TimePicker 获取时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54927084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com