我有以下代码:
getWeek(addDays(Date, amount: 6))
func addDays(date: NSDate, amount: Int) -> NSDate {
// calculation $additionalDays
let additionalDays = amount
// adding $additionalDays
let components = NSDateComponents()
components.day = additionalDays
// important: NSCalendarOptions(0)
let futureDate = NSCalendar.currentCalendar()
.dateByAddingComponents(components, toDate: date, options: NSCalendarOptions(rawValue: 0))
return futureDate!
}
func getWeek(today:NSDate)->Int? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.WeekOfYear, fromDate: today)
let weekNumber = myComponents.weekOfYear
return weekNumber
}
getWeek(addDays(Date, amount: 6)) 中的日期返回 dec 27, 2015, 7:16PM
这是正确的(下周日)但是,如果我尝试返回该日期的周数,它返回 1 而这应该是 53。我如何获得正确的周数?
最佳答案
根据 Apple 开发者技术支持:
27 Dec 2015 is week 52, not week 53. The first day of week 53 in 2015 is 28 Dec.
Regardless, you’re correct that the value returned by your
getWeek()function does not match ISO 8601. The reason for that is that you’re using NSCalendarIdentifierGregorian rather than NSCalendarIdentifierISO8601. There are /lots/ of different ways to do week-of-year calculations. I can go into the gory details if you’d like, but the ‘take home’ message here is that, if you want ISO 8601 week calculations, you should use NSCalendarIdentifierISO8601.
有了这个改变,getWeek() 开始产生符合 ISO 8601 的结果。具体来说:
print(self.getWeek(self.dateFromFixedFormatString("2015-12-27 12:34")))
print(self.getWeek(self.dateFromFixedFormatString("2015-12-28 12:34")))
打印:
假设:
func dateFromFixedFormatString(dateStr: String) -> NSDate {
let df = NSDateFormatter()
df.locale = NSLocale(localeIdentifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
return df.dateFromString(dateStr)!
}
func getWeek(today:NSDate) -> Int {
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierISO8601)!
let myComponents = myCalendar.components(.WeekOfYear, fromDate: today)
let weekNumber = myComponents.weekOfYear
return weekNumber
}
因此,任何声明 GregorianCalendar 在我的代码中不起作用的人都是正确的,并且应该专门使用 NSCalendarIdentifierISO8601。 NSCalendar.currentCalendar() 不会自动获取 ISO 日历。 (很奇怪)
关于swift - NSDate 返回错误的周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34402001/
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c
我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file
我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe
在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa