比较Swift中的日期而忽略当前时区

时间:2018-06-25 09:52:11

标签: swift

在Swift中,我可以使用Calendar.current.dateComponents

找到两个日期之间的差异

问题在于,这相对于我当前的时区有所不同。

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd HH:mm XXX"

let from = zoneFormatter.date(from: "2018-03-25 00:00 +00:00")!
let to = zoneFormatter.date(from: "2018-03-26 00:00 +00:00")!

let components = Calendar.current.dateComponents([.month, .day, .hour, .minute], from: from, to: to)
// components is 1 day, 1 hour, because I am in UK and Daylight Savings started on 25 March.

如何获取以dateComponents返回的相同格式指定的两个瞬间之间的绝对差?

2 个答案:

答案 0 :(得分:0)

日期格式字符串不正确

看起来像您使用的日期格式不正确。指定的日期"2018-03-25 00:00 +00:00"的日期格式实际上是"yyyy-MM-dd HH:mm ZZZZZ"。试试这种格式,它应该可以解决问题。

为什么时区之间的比较格式不正确?

这是因为格式字符串的timeZone组件不正确。这意味着在比较中不会考虑timeZone。

答案 1 :(得分:0)

可以通过如下设置系统默认时区来更改@Entity @Table(name = "account") @JsonInclude(JsonInclude.Include.NON_NULL) public class Account implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_generator") @SequenceGenerator(name = "account_seq_generator", sequenceName = "account_seq") @Column(name = "naccount_id") public Integer nAccountId; @Column(name = "namount") public String nAmount; @Column(name = "sacct_desc") public String sAcctDesc; @Column(name = "naccount_cpc_mapping_id") public Integer nAccountCPCMappingId; @Column(name = "nindirect_cost_rate") public Integer nIndiretCostRate; @Column(name = "nagency_id") public Integer nAgencyId; @Column(name = "ndept_id") public Integer nDeptId; @Column(name = "sgrant_num") public String sGrantNum; @Column(name = "dstart_date") public Timestamp dStartDate; @Column(name = "dend_date") public Timestamp dEndDate; @Column(name = "slocation") public String sLocation; @Column(name = "sclient_acct_id") public String sClientAcctId; @Column(name = "ninvestigator_id") public Integer nInvestigatorId; @Column(name = "ninst_id") public Integer nInstId; @Column(name = "ntemp_account_id") public Integer nTempAccountId; @ManyToOne(optional = true, cascade = { CascadeType.MERGE }) @JoinColumn(name = "ndept_id", insertable = false, updatable = false) public Department department; @ManyToOne(optional = true, cascade = { CascadeType.ALL }) @JoinColumn(name = "ninvestigator_id", insertable = false, updatable = false) public Investigator investigator; @ManyToOne(optional = true, cascade = { CascadeType.ALL }) @JoinColumn(name = "naccount_cpc_mapping_id", insertable = false, updatable = false) public AccountCPCMapping accountCPC; 的时区:

Calendar.current