在 android java 中转换并获取 UTC+0 中的 DateTime 并比较 DateTime 的

Transform and Get DateTime in UTC+0 in android java and compare DateTime's

我看了很多类似问题的答案,但找不到我打算做什么。

我正在开发一个 android 应用程序,我需要检查当前设备日期时间(变量 TimeZone)是否在两个日期时间(以 UTC+0 指定)之间。

这里是一个伪例子:

if( (UTC+0 DateTime of actual week friday at 23:00:00) 
    < 
    (device DateTime transformed to UTC+0)
    <
    (UTC+0 DateTime of actual week sunday at 23:00:00) )
{
    #some code here
}

我不知道如何获取第一个和第三个DateTimes,我可以通过以下方式获取日期:

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
if(Calendar.FRIDAY < c.get(Calendar.DAY_OF_WEEK) < Calendar.SUNDAY)

但我仍然需要在 UTC+0 中指定的 23:00:00 实际周周五和周日的 DateTime。

我想在比较之前将实际设备 DateTime 转换为 UTC+0,我尝试使用 CalendarJoda Time utils 但是我找不到获取当前 UTC+0 日期时间并将非 UTC+0 日期时间转换为 UTC+0 的简单方法。

肯定很简单但是找不到方法

DateTime date = DateTime.now();            
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z (z)");

输出:2015 年 7 月 26 日星期日 04:33:19 GMT+0530 (IST)

这会给你一些想法

已编辑

使用这个

DateTime currentTime = DateTime.now( DateTimeZone.UTC ); 

它会工作你可以用任何时区初始化它作为

DateTime.now(DateTimeZone zone) 

也试试这个

DateTime currentTime = DateTime.now( DateTimeZone.getDefault() );

比较方法:isBeforeisAfterisEqual

你太辛苦了。

比较DateTime objects. Joda-Time handles that for you automatically. Internally Joda-Time tracks a DateTime as a number of milliseconds fro the epoch in UTC时无需调整时区。因此,通过比较可以很容易地看出哪个先于或后于。

只需在 DateTime, isBefore, isAfter, and isEqual 上调用比较方法即可。

Boolean inRange = ( x.isAfter( start ) || x.isEqual( start ) ) && x.isBefore ( stop ) ;

如果 DateTime 对象恰好都具有相同的时区 (DateTimeZone), you make use of the handy Interval class.

Interval interval = new Interval( start , stop ) ;
Boolean inRange = interval.contains( x ) ;

至于找到 next/last 星期一、星期日等等,搜索 Whosebug,因为之前已经解决过很多次(比如 this), as have all the topics in your Question actually. Such as this and this and .

我上面的代码和 Interval class 在它们的比较逻辑中都使用了 "Half-Open" 方法。开头是包含,结尾是不包含Search whosebug.com 了解更多。