我想寻求最佳实践或方法来改进我正在解决的非常具体的问题的代码,其中涉及采用 4 个字符的有限长度字符串来表示未来的日期,它可能是从现在开始的一周或一个月等。并且与现在进行比较,如果已经过去了太多天,那么就做一些事情。
我认为我可以通过创建一个始终以“17”开头的字符串,插入四位数字并用四个零填充其余部分来做到这一点,我不需要它在一天左右的时间内非常准确。
有几点需要注意:
我知道用户可以在 iPhone 设置中手动更改日期。我计划将来检查服务器日期并第二次比较,但这主要是一个离线应用程序
我收到的 4 个字符的字符串是我将该字符串输入到蓝牙外围设备数据字段的人。该字符串将来保留为字母或不全部是数字的能力,因此我首先检查所有字符是否都是整数,然后再将其转换为日期
我的代码可能不是最高效的
这可能听起来像一个愚蠢的问题,但这就是我正在使用的参数
if let reservationDate = node?.user?.dateValue {
let arr = Array(reservationDate)
//I am checking whether the index exists probably unnecessary but being overly cautious
if arr.indices.contains(0) {
if let char1 = Int(String(arr[0])){
if arr.indices.contains(1) {
if let char2 = Int(String(arr[1])){
if arr.indices.contains(2) {
if let char3 = Int(String(arr[2])){
if arr.indices.contains(3) {
if let char4 = Int(String(arr[3])){
let deviceValue = char1 + char2 + char3 + char4
let fullEpochValue = "17" + String(deviceValue) + "0000"
if let fullEpochValueToInt = TimeInterval(fullEpochValue){
let savedDate = Date(timeIntervalSince1970: fullEpochValueToInt)
let now = Date()
let calendar = Calendar.current
let difference = calendar.numberOfDaysBetween(savedDate, and: now)
if difference > 2 {
//do something if greater than 2 days
}
}
}
}
}
}
}
}
}
}
}
您认为还有什么需要改进的地方吗?
一个想法:
最简单的方法是使用 4 个字符长的十六进制数字,从而得到 65536 种可能的天数(179 年)。十六进制数字的优点是易于使用和转换。
设置一个开始日期,例如纪元(1970 年 1 月 1 日),并计算从该日期开始的天数。从那时起,基于 The Epoch 的 Unix 时间使用秒,但由于一天有 86400 秒,因此很容易计算天数,反之亦然。
import time
import datetime
# gives the 4 character string of the day
a=hex(int(time.time()/86400))[2:]
print(a) #19828
# converting back
b=int(a,16)*86400
print(datetime.datetime.utcfromtimestamp(b).strftime("%Y-%m-%d")) #'2024-04-15'
如果这个时间范围不够,你可以使用4个字符长的字符串来表示某一天,那么如果你只使用大写或小写字母,你有26^4=456976种可能性。如果将数字相加,则有 36^4=1679616 种可能性,加上上下字符和数字,则有 62^4=14776336 种可能性(约 40000 年)。