在Java中将整数日期/时间转换为unix时间戳?
这主要适用于android,但也可以在Java中使用。我有这些侦听器:
int year, month, day, hour, minute;
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
year = year;
month = monthOfYear;
day = dayOfMonth;
}
};
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
minute = minute;
}
};
如何将 int 年、月、日、小时、分钟; 转换为 unix 时间戳?如果没有 Date
类,这可能吗?
This mainly applies to android, but could be used in Java. I have these listeners:
int year, month, day, hour, minute;
// the callback received when the user "sets" the date in the dialog
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
year = year;
month = monthOfYear;
day = dayOfMonth;
}
};
// the callback received when the user "sets" the time in the dialog
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
minute = minute;
}
};
How could I convert int year, month, day, hour, minute;
to a unix timestamp? Is this possible without the Date
class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好的,那么就使用 Calendar,因为无论如何它都优于 Date:
Calendar 在调用
getTimeMillis()
之前不会执行任何计算,并且被设计为比Date
更高效。Okay, use Calendar then, since that's preferred to Date anyway:
Calendar won't do any computations until
getTimeMillis()
is called and is designed to be more efficient thanDate
.我假设您想避免对象开销,因此我不建议使用任何 Date 或 Calendar 类;相反,您可以直接计算该值。
计算从 1970 年 1 月 1 日到所选年/月/日的天数并将其乘以
24 * 3600
,然后加上小时 * 3600 + 分钟 * 60
以获取从 1970-01-01 00:00 到所选日期的秒数和时间。有众所周知的算法来计算日期之间的天数。
I'm assuming you want to avoid object overhead so I'm not suggesting any Date or Calendar classes; rather, you can calculate the value directly.
Calculate the number of days from Jan 1 1970 to the chosen year/month/day and multiply that by
24 * 3600
, then addhour * 3600 + minute * 60
to get the number of seconds from 1970-01-01 00:00 to the chosen date and time.There are well known algorithms for calculating the days between dates.
由于我还想考虑夏令时以及当地时区,因此在搜索了几个小时所有可能的解决方案后,对我有用的方法如下:
Since I wanted to account for daylight saving as well, along with local timezone, so after searching for hours all the possible solutions, what worked for me was as follows: