我有一些代码可以获取今天和另一个时间字符串之间的时间差。
使用 NSTimer.scheduledTimerWithTimeInterval 每秒刷新显示。
除计时器达到 0 外,一切正常。0 显示两次。
例子:
3,2,1,0,0,-1,-2
下面是我在 Playground 上完成的代码:
//: Playground - Time Countdown
import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()
class MyClass {
var totalSecondsText = ""
init(classSecondsText: String){
totalSecondsText = classSecondsText
}
@objc func ontimer(timer:NSTimer!){
let total = determineTimeDifference(totalSecondsText)
let (hour,min,sec) = secondsConverter(total)
if hour >= 1 {
if min >= 1 {
NSLog(String(hour)+"h "+String(min)+"m")
}else {
NSLog(String(hour)+"h")
}
}else{
if min >= 1{
NSLog(String(min)+"m "+String(sec)+"s")
} else if min > -1 {
NSLog(String(sec)+"s")
} else if min <= -1 {
NSLog(String(min)+"m")
}
}
}
func determineTimeDifference(timeInputed: String) -> Int {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let finalDate = dateFormat.dateFromString(raceTime)
let differenceTimeInSeconds = (finalDate?.timeIntervalSinceNow)!
return differenceInSeconds
}
func secondsConverter (seconds : Int) -> (Int , Int, Int){
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
}
// Add +1 minute on time to test.
var dateString = "2016-08-31T6:49:00Z"
NSTimer.scheduledTimerWithTimeInterval(1, target: MyClass(classSecondsText: dateString), selector: #selector(MyClass.ontimer(_:)), userInfo: nil, repeats: true)
知道哪里出了问题吗?
更新:
正如所 promise 的,这是针对此问题的错误修复:
func determineTimeDifference(timeInputed: String) -> Int {
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let finalDate = dateFormat.dateFromString(raceTime)?.timeIntervalSince1970
let dateNow = NSDate().timeIntervalSince1970
let differenceTimeInSeconds = Int(finalDate) - Int(dateNow)
return differenceInSeconds
}
最佳答案
您的代码提供得很好,并且条件设置正确。
看起来 Data.components 没有正确处理计数差异。这可能是由秒组件的舍入引起的。
如果在时刻之前计数,当当前时间和最终时间相等时,(达到 0,0),结果会出现错误 -1。 p>
当我用额外的打印更新您的代码时,显示如下:
CURRENT date: 2016-08-31 13:10:57 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: 2s (BAD)
CURRENT unix: 1472649057.28685 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: -3.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
2s
CURRENT date: 2016-08-31 13:10:58 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: 1s (BAD)
CURRENT unix: 1472649058.28734 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: -2.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
1s
CURRENT date: 2016-08-31 13:10:59 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: 0s (BAD)
CURRENT unix: 1472649059.28731 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: -1.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
0s
CURRENT date: 2016-08-31 13:11:00 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: 0s (OK)
CURRENT unix: 1472649060.28731 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: 0.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
0s
CURRENT date: 2016-08-31 13:11:01 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: -1s (OK)
CURRENT unix: 1472649061.28731 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: 1.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
-1s
CURRENT date: 2016-08-31 13:11:02 +0000 - FINAL date: 2016-08-31 13:11:00 +0000
-->> diff by DateComponents: -2s (OK)
CURRENT unix: 1472649062.28729 - FINAL unix: 1472649060.0
--->>> Diff in UNIX: 2.0s (counted as Rounded CURRENT UNIX - FINAL UNIX)
-2s
因此,如果使用四舍五入的 unix 时间之间的差异进行计数,结果是正确的。
结论:误差有时出现在等式之前,有时出现在等式之后。这取决于该脚本启动的时间。如果按数据组件计数以错误开始,则在 0、0 之后进行清理。如果以正确结果开始计数,则结果开始带来错误结果。这就是零出现两次的原因 - 在结果改变其精确状态的那一刻。
关于swift - NSTimer 倒计时产生两次 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39242509/
我写了一个非常简单的rake任务来尝试找到这个问题的根源。namespace:foodotaskbar::environmentdoputs'RUNNING'endend当在控制台中执行rakefoo:bar时,输出为:RUNNINGRUNNING当我执行任何rake任务时会发生这种情况。有没有人遇到过这样的事情?编辑上面的rake任务就是写在那个.rake文件中的所有内容。这是当前正在使用的Rakefile。requireFile.expand_path('../config/application',__FILE__)OurApp::Application.load_tasks这里
我正在寻找一个用ruby演示计时器的在线示例,并发现了下面的代码。它按预期工作,但这个简单的程序使用30Mo内存(如Windows任务管理器中所示)和太多CPU有意义吗?非常感谢deftime_blockstart_time=Time.nowThread.new{yield}Time.now-start_timeenddefrepeat_every(seconds)whiletruedotime_spent=time_block{yield}#Tohandle-vesleepinteravalsleep(seconds-time_spent)iftime_spent
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:HowdoIgeneratealistofnuniquerandomnumbersinRuby?我想做的事:Random.rand(0..10).timesdoputsRandom.rand(0..10)end但如果随机数已经显示过,则无法再次显示。如何最轻松地做到这一点?
许多正则表达式引擎在单行字符串中匹配.*两次,例如,在执行基于正则表达式的字符串替换时:根据定义,第一个匹配项是整个(单行)字符串,正如预期的那样。在许多引擎中有第二个匹配项,即空字符串;也就是说,即使第一个匹配项消耗了整个输入字符串,.*仍会再次匹配,然后匹配输入字符串末尾的空字符串。注意:要确保只找到一个匹配项,请使用^.*我的问题是:这种行为有充分的理由吗?一旦输入字符串被完全使用,我不希望再次尝试找到匹配项。除了反复试验之外,您能否从支持的文档/正则表达式方言/标准中收集到哪些引擎表现出这种行为?更新:revo'shelpfulanswer解释当前行为的方式;至于潜在的原因,请
重新定义Float#/似乎没有效果:classFloatdef/(other)"magic!"endendputs10.0/2.0#=>5.0但是当另一个中缀运算符Float#*被重新定义时,Float#/突然采用了新的定义:classFloatdef/(other)"magic!"enddef*(other)"spooky"endendputs10.0/2.0#=>"magic!"我很想知道是否有人可以解释这种行为的来源,以及其他人是否得到相同的结果。ruby:ruby2.0.0p353(2013-11-22)[x64-mingw32]要快速确认错误,请运行thisscript.
有时您会制作特定于项目的gem。这有助于将一些“责任”从主Rails应用程序中抽象出来并转移到一个更加模块化的地方。gem将位于您应用程序的此处:gem'example_gem',path:'./example_gem'你捆绑,一切都很好。现在,您gitinitgem并将其存储在github上它自己的repo中。您尝试这样做以使其对开发人员友好:group:development,:testdogem'example_gem',path:'./example_gem'endgroup:productiondogem'example_gem',github:'company/exampl
gemspec语义版本控制运算符~>(又名twiddle-wakka,又名pessimistic运算符)允许限制gem版本但允许进行一些升级。我经常看到它可以读作:"~>3.1"=>"Anyversion3.x,butatleast3.1""~>3.1.1"=>"Anyversion3.1.x,butatleast3.1.1"但是有了一个数字,这条规则就失效了:"~>3"=>"Anyversionx,butatleast3"*NOTTRUE!*"~>3"=>"Anyversion3.x"*True.Butwhy?*如果我想要“任何版本3.x”,我可以只使用“~>3.0”,这是一致的。就
require'openssl'ifARGV.length==2pkcs12=OpenSSL::PKCS12.new(File.read(ARGV[0]),ARGV[1])ppkcs12.certificateelseputs"Usage:load_cert.rb"end运行它会在Windows上产生错误,但在Linux上不会。错误:OpenSSL::PKCS12::PKCS12Error:PKCS12_parse:macverifyfailurefrom(irb):21:ininitializefrom(irb):21:innewfrom(irb):21fromC:/Ruby192/
我无法让ruby成功地require'tk'。我正在使用rvm、ruby2.0.0、ActiveTcl-8.6和Ubuntu12.04LTS。我已经运行了随ActiveTcl一起提供的wish,它似乎正在运行。我查看了RVM网站http://rvm.io/integration/tk和几个像这样的StackOverflow问题RVMRubywithTKinstallation(OSX).我在不同版本的ruby上多次尝试rvmreinstall2.0.0--enable-shared--enable-pthread--with-tk--with-tcl但没有成功。有什么想法吗?当
我在Ruby中有一个包含5个空数组的数组。我正在尝试使用运算符将字符串插入第一个数组,但结果是字符串被插入所有数组。请帮助我理解这一点。预期的输出是:#=>[["car"],[],[],[],[]]但我得到:#=>[["car"],["car"],["car"],["car"],["car"]]IRB转储:1.9.3-p194:001>output=Array.new(5,[])=>[[],[],[],[],[]]1.9.3-p194:002>output.inspect=>"[[],[],[],[],[]]"1.9.3-p194:003>output[0].inspect=>"[]"