- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
鉴于设备中的当前用户设置,是否可以确定给定日期/时间是否在夏令时?我不是在问手机当前是否启用了夏令时。我需要知道使用手机中的当前设置的给定( future )日期是否会在 DST 下。我可以使用 Date()、Calendar() 或 Joda。我也很好奇类/方法如何处理歧义,例如本周日凌晨 2:30(北美)。那个时间不会存在,因为我们会过去。同样,在秋天,当我们后退时,凌晨 1:30 会出现两次。第一个 1:30 AM 不在夏令时,但第二个是。
最佳答案
确定纪元时间是否在给定时区的 DST 中很容易。
public static boolean isInDst(TimeZone tz, Date time)
{
Calendar calendar = Calendar.getInstance(tz);
calendar.setTime(time);
// or supply a configured calendar with TZ as argument instead
return calendar.get(Calendar.DST_OFFSET) != 0;
}
就 API 而言,将本地时间转换为纪元看起来很容易
Calendar calendar = Calendar.getInstance(tz);
calendar.set(year, month, date, hourOfDay, minute);
Date epoch = calendar.getTime();
但由于模糊和间隙值变得棘手。
我已经编写了一个实用程序来测试模糊值和间隙值,目的是仅使用 Java API(没有 Joda-Time 等),但请非常仔细地阅读 javadoc 评论,了解仅在未来使用它。此外,我不会在遥远的 future 使用它,因为地方当局不断更改 DST 规则。我在南澳大利亚(南半球 +9:30/+10:30)、纽约和豪勋爵岛(夏令时半小时!+10:30/+11:00)测试了此实用程序,但时间很棘手,所以使用它需要您自担风险。
/**
* Utility method to help handle Day Light Savings transitions. It
* calculates possible time values the parameters could mean and returns all
* possible values.
*
* This method should ONLY be used for detecting ambiguous times in the
* future, and not in the past. This method WILL fail to detect ambiguous
* times in the past when the time zone would observe DST at the specified
* time, but no longer does for current and future times. It also can fail
* to detect ambiguous time in the past if at the specified time the DST
* offset was different from the latest DST offset.
*
* This method can fail to detect potentially ambiguous times if the
* calendar uses leap seconds and leap second(s) are added/removed during
* DST transition.
*
* @param calendar
* the calendar to use, must have the correct time zone set. This
* calendar will be set, do not rely on the value set in the
* calendar after this method returns.
* @param year
* @param month
* @param dayOfMonth
* zero based month index as used by {@link Calendar} object.
* @param hourOfDay
* @param minute
* @return Array of {@link Date} objects with each element set to possible
* time the parameters could mean or null if the parameters are not
* possible, e.g. fall into the missing hour during DST transition,
* or complete garbage. One element array means there is only one
* non-ambiguous time the parameters can mean, that is, there is no
* DST transition at this time. Two element array means the
* parameters are ambiguous and could mean one of the two values. At
* this time more than two elements can not be returned, but
* calendars are strange things and this limit should not be relied
* upon.
* @throws IllegalArgumentException
* if setting the specified values to the calendar throws same
* exception {@link Calendar#set(int, int, int, int, int)} or if
* invalid values are found but are not due to DST transition
* gap.
*/
public static Date[] getPossibleTimes(
Calendar calendar,
int year, int month, int dayOfMonth, int hourOfDay, int minute)
throws IllegalArgumentException
{
calendar.clear();
try
{
// if calendar is set to non-lenient then setting time in the gap
// due to DST transition will throw exception
calendar.set(
year,
month,
dayOfMonth,
hourOfDay,
minute
);
}
catch (IllegalArgumentException ex)
{
if (calendar.isLenient())
{
throw ex;
}
return null;
}
// if validated fields do not match input values
// this can be when set hour is missing due to DST transition
// in which case calendar adjusts that hours and returns values
// different to what was set
if (
calendar.get(Calendar.YEAR) != year
|| calendar.get(Calendar.MONTH) != month
|| calendar.get(Calendar.DAY_OF_MONTH) != dayOfMonth
|| calendar.get(Calendar.HOUR_OF_DAY) != hourOfDay
|| calendar.get(Calendar.MINUTE) != minute
)
{
// the values are not possible.
return null;
}
Date value1 = calendar.getTime();
int dstSavings = calendar.getTimeZone().getDSTSavings();
if (dstSavings == 0)
{
return new Date[] { value1 };
}
// subtract DST offset
calendar.add(Calendar.MILLISECOND, - dstSavings);
// check if the resulting time fields are same as initial times
// this could happen due to DST transition, and makes the input time ambiguous
if (
calendar.get(Calendar.YEAR) == year
&& calendar.get(Calendar.MONTH) == month
&& calendar.get(Calendar.DAY_OF_MONTH) == dayOfMonth
&& calendar.get(Calendar.HOUR_OF_DAY) == hourOfDay
&& calendar.get(Calendar.MINUTE) == minute
)
{
Date value2 = calendar.getTime();
return new Date[] { value2, value1, };
}
// checking with added DST offset does not seem to be necessary,
// but time zones are confusing things, checking anyway.
// reset
calendar.setTime(value1);
// add DST offset
calendar.add(Calendar.MILLISECOND, dstSavings);
// same check for ambiguous time
if (
calendar.get(Calendar.YEAR) == year
&& calendar.get(Calendar.MONTH) == month
&& calendar.get(Calendar.DAY_OF_MONTH) == dayOfMonth
&& calendar.get(Calendar.HOUR_OF_DAY) == hourOfDay
&& calendar.get(Calendar.MINUTE) == minute
)
{
Date value2 = calendar.getTime();
return new Date[] { value1, value2, };
}
return new Date[] { value1, };
}
只是为了展示一些测试结果,这里是测试方法:
public static void test2()
{
TimeZone tz = TimeZone.getTimeZone("America/New_York");
System.out.format("id=%s\n", tz.getID());
System.out.format("display=%s\n", tz.getDisplayName());
System.out.format("raw offset=%f hours\n", tz.getRawOffset() / 1000f / 60f / 60f);
System.out.format("dstSaving=%f minutes\n", tz.getDSTSavings() / 1000f / 60f);
System.out.format("observesDST=%b\n", tz.observesDaylightTime());
System.out.format("\n");
// Time Tuple class simply holds local time, month is zero based as per Calendar
TimeTuple [] testTimes = new TimeTuple[]{
new TimeTuple(2014, 2, 9, 1, 59), // Non-ambiguous standard NY
new TimeTuple(2014, 2, 9, 2, 00), // GAP NY
new TimeTuple(2014, 2, 9, 2, 59), // GAP NY
new TimeTuple(2014, 2, 9, 3, 00), // Non-ambiguous DST NY
new TimeTuple(2014, 10, 2, 0, 59), // Non-ambiguous DST NY
new TimeTuple(2014, 10, 2, 1, 00), // Ambiguous DST in NY
new TimeTuple(2014, 10, 2, 1, 59), // Ambiguous DST in NY
new TimeTuple(2014, 10, 2, 2, 00), // Non-ambiguous standard NY
};
Calendar calendar = GregorianCalendar.getInstance(tz);
Date[] possibleTimeValues = null;
for (TimeTuple tt: testTimes)
{
possibleTimeValues = getPossibleTimes(
calendar,
tt.year, // year
tt.month, // zero based month
tt.dayOfMonth, // date
tt.hourOfDay, // hours
tt.minute // minutes
);
printTimeAmbiguouity(calendar, possibleTimeValues, tt);
}
}
static DateFormat TZ_FORMAT = new SimpleDateFormat("Z zzzz");
static DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S Z zzzz");
public static void printTimeAmbiguouity(Calendar calendar, Date[] possibleTimeValues, TimeTuple tt)
{
TZ_FORMAT.setTimeZone(calendar.getTimeZone());
DATE_FORMAT.setTimeZone(calendar.getTimeZone());
System.out.format("\tinput local time %s ----- ", tt.toString());
if (possibleTimeValues == null)
{
System.out.format("Impossible/invalid/DST_gap\n");
calendar.set(tt.year, tt.month, tt.dayOfMonth, tt.hourOfDay, tt.minute);
Date adjustedTime = calendar.getTime();
calendar.add(Calendar.HOUR, -6);
Date limitTime = calendar.getTime();
Date preTranstionTime = getPreviousTransition(calendar, adjustedTime, limitTime);
Date postTranstionTime = new Date(preTranstionTime.getTime() + 1);
System.out.format(
"\tadjusted %s\n\ttranstion from %s\n\t to %s\n",
DATE_FORMAT.format(adjustedTime),
DATE_FORMAT.format(preTranstionTime),
DATE_FORMAT.format(postTranstionTime));
}
else if (possibleTimeValues.length == 1)
{
System.out.format("NonAmbiguous Valid\n");
System.out.format("\ttimezone %s\n", TZ_FORMAT.format(possibleTimeValues[0]));
}
else
{
System.out.format("Ambiguous\n");
for (Date time: possibleTimeValues)
{
System.out.format("\tpossible value %s\n", TZ_FORMAT.format(time));
}
}
System.out.format("\n");
}
我没有包括 getPreviousTransition() 方法,因为我认为代码更不适合生产。
测试输出:
id=America/New_York
display=Eastern Standard Time
raw offset=-5.000000 hours
dstSaving=60.000000 minutes
observesDST=true
input local time 2014-02-09 01:59 ----- NonAmbiguous Valid
timezone -0500 Eastern Standard Time
input local time 2014-02-09 02:00 ----- Impossible/invalid/DST_gap
adjusted 2014-03-09 03:00:00.0 -0400 Eastern Daylight Time
transtion from 2014-03-09 01:59:59.999 -0500 Eastern Standard Time
to 2014-03-09 03:00:00.0 -0400 Eastern Daylight Time
input local time 2014-02-09 02:59 ----- Impossible/invalid/DST_gap
adjusted 2014-03-09 03:59:00.0 -0400 Eastern Daylight Time
transtion from 2014-03-09 01:59:59.999 -0500 Eastern Standard Time
to 2014-03-09 03:00:00.0 -0400 Eastern Daylight Time
input local time 2014-02-09 03:00 ----- NonAmbiguous Valid
timezone -0400 Eastern Daylight Time
input local time 2014-10-02 00:59 ----- NonAmbiguous Valid
timezone -0400 Eastern Daylight Time
input local time 2014-10-02 01:00 ----- Ambiguous
possible value -0400 Eastern Daylight Time
possible value -0500 Eastern Standard Time
input local time 2014-10-02 01:59 ----- Ambiguous
possible value -0400 Eastern Daylight Time
possible value -0500 Eastern Standard Time
input local time 2014-10-02 02:00 ----- NonAmbiguous Valid
timezone -0500 Eastern Standard Time
关于java - Android 确定给定的日期/时间是否在设备上的夏令时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15295343/
在下面的代码中,我得到一个 uninitialized value警告,但仅限于第二个 given/when例子。为什么是这样? #!/usr/bin/env perl use warnings; u
整个“开关”功能是否已成为实验性的?在没有 Perl 的 future 版本破坏我的代码的情况下,我可以依赖其中的某些部分吗?一般来说,将稳定功能更改为实验性的政策是什么? 背景use feature
有没有办法在一个条件语句中写出如下语句? a和b不能同时等于5。 (a可以是5,b可以是5,但是a AND b不能是5) 最佳答案 正如克里斯指出的那样,您要查找的是逻辑异或,相当于逻辑不等于 !=:
我正在寻找一种算法来找到给定 n 条线段的所有交点。以下是来自 http://jeffe.cs.illinois.edu/teaching/373/notes/x06-sweepline.pdf 的伪
数组中有 N 个元素。我可以选择第一项最多 N 次,第二项最多选择 N-1 次,依此类推。 我有 K 个 token 要使用并且需要使用它们以便我可以拥有最大数量的项目。 arr = [3, 4, 8
我正在尝试修复法语文本中的语法性别,想知道是否有办法从某个词条中获取所有单词的列表,以及是否可以在此类列表中进行查找? 最佳答案 尝试: import spacy lemma_lookup = spa
我正在为 Win32 编写一个简单的自动化测试应用程序。它作为一个单独的进程运行,并通过 Windows API 访问目标应用程序。我可以阅读窗口层次结构,查找标签和文本框,并通过发送/发布消息等来单
在 nodeJs 中使用 Sequelize 时,我从 Sequelize 收到此错误,如下所示: { [SequelizeUniqueConstraintError: Validation erro
本文https://arxiv.org/pdf/1703.10757.pdf使用回归激活映射 (RAM) - 而不是类激活映射 (CAM) 来解决问题。有几篇文章描述了如何实现 CAM。但是我找不到
我正在研究 Mach 动态链接器 dyld。这个问题适用于所有 Apple 平台,但很高兴得到特定于平台的答案;我正在使用 ObjC,但如果对你有用的话,我也很乐意翻译 Swift。 The rele
我有一个包含数千个 Instagram 用户 ID 的列表。我如何获得他们的 Instagram 用户名/句柄? 最佳答案 你必须使用这个 Instagram API: https://api.ins
我在下面的代码: def main(args: Array[String]) { val sparkConf = new SparkConf().setAppName("Spark-Hbase").s
我有一个表格,其中包含从 1 到 10 的数字。(从 D2 到 M2) 假设A1中有03/09/2019 并且在B1中有06/09/2019 并且在C1中有Hello 在A 列中,我有多个系列的单词,
我想在给定服务对应的 URI 的情况下检索服务的注释(特别是 @RolesAllowed )。这是一个例子: 服务: @GET @Path("/example") @RolesAllowed({ "B
我看到 OraclePreparedStatementexecuteQuery() 表现出序列化。也就是说,我想使用相同的连接对 Oracle 数据库同时运行两个查询。然而,OraclePrepare
import java.util.Scanner; public class GeometricSumFromK { public static int geometricSum(int k,
我创建了一个抽象基类Page,它说明了如何构建动态网页。我正在尝试想出一种基于作为 HttpServletRequest 传入的 GET 请求生成 Page 的好方法。例如... public cla
我的字符串是一条短信,采用以下两种格式之一: 潜在客户短信: 您已收到 1 条线索 标题:我的领导 潜在客户 ID:12345-2365 警报设置 ID:890 短信回复: 您已收到 1 条回复 标题
我在 python 中有以下代码: class CreateMap: def changeme(listOne, lisrTwo, listThree, listFour, listfive):
这是在 Hibernate 上运行的 JPA2。 我想检索相同实体类型的多个实例,给定它们的 ID。其中许多已经在持久性上下文和/或二级缓存中。 我尝试了几种方法,但似乎都有其缺点: 当我使用 ent
我是一名优秀的程序员,十分优秀!