We want to assign the result Once at 23:00 to number 1, but does not move the following source.
Perhaps, I think not been able conversion of type String.
I want you to tell me the solution
import UIKit
let now = NSDate() // gettime
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "ja_JP")
dateFormatter.dateFormat = "hh" // o`clock
print(dateFormatter.stringFromDate(now)) // convert to String
if now = 23 {
number1 = result
result = 0
}
let now = NSDate() // gettime
let calendar = NSCalendar.autoupdatingCurrentCalendar()
// If you want to know the hour in a particular time zone, set it here.
// For example, to get the time in Japan:
// calendar.timeZone = NSTimeZone(name: "Asia/Tokyo")!
// By default, the calendar uses the system time zone setting.
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: now)
if hour == 23 {
print("It is the appointed hour.")
}
Related
I am doing some date math and before doing so am trying to programatically adjust the time associated with a date based on its current value. In the code below I am able to set the hours and minutes to 00/00 but I have to know the offset and manually set the value. Below is my code and next to each print statement I have listed the value I am getting. Any assistance in pointing out the error I am making will be appreciated. I wonder if it is a timezone issue relative to GMT.
Chris
func AdjustDateTime(vooDate: Date) -> Date {
let date = vooDate
let _ = print("date")
let _ = print(date) // returns 2021-10-25 06:00:00 +000
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let year = components.year
let month = components.month
let day = components.day
let hour = components.hour
let minute = components.minute
let _ = print("hour")
let _ = print(hour!) // returns 0 even though the date above say 06
let _ = print("minute")
let _ = print(minute!) // returns 0
var comps = DateComponents()
comps.year = year
comps.month = month
comps.day = day! + 1
comps.hour = -06 // setting manually, would like to do so programatically
comps.minute = 00
let returnDate: Date = Calendar.current.date(from: comps)!
let _ = print("Return Date")
let _ = print(returnDate) // returns 2021-10-26 00:00:00 +0000, which is what I want
return returnDate
}
Setting the time zone as indicated by Jacob was the key to solving the problem. In the code where I read in the JSON file I modified my dateFormatter to what's shown below. This returns a date object as shown below the code. Now I do not need to worry about the hours, since they are 0. From there it is easy to add 1 day with a function, shown below. Before doing my date math I make the same adjustments to a date in the future, i.e. timezone and locale, and I get the correct difference between the two dates which was the ultimate goal. Thank you for the assistance.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // added
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0) // added
2021-10-25 00:00:00 +0000
func AdjustDateTime(vooDate: Date) -> Date {
return Calendar.current.date(byAdding: .day, value: 1, to: vooDate)!
}
I'm working on calendar with this pod https://github.com/miraan/CalendarDateRangePickerViewController. I changed months names but can't change days of week.
I tried to add components.calendar?.locale = Locale(identifier: "ru_RU") and dateFormatter.locale = Locale.autoupdatingCurrent but nothing has changed.
func getWeekdayLabel(weekday: Int) -> String {
var components = DateComponents()
components.calendar = Calendar.current
components.calendar?.locale = Locale(identifier: "ru_RU")
components.weekday = weekday
let date = Calendar.current.nextDate(after: Date(), matching: components, matchingPolicy: Calendar.MatchingPolicy.strict)
if date == nil {
return "E"
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEEE"
return dateFormatter.string(from: date!)
}
Your code is needlessly overcomplicated.
What you want to get is just weekday symbols. Shortest form as possible.
And Calendar has dedicated property for this: veryShortStandaloneWeekdaySymbols.
And the result function is:
func getWeekdayLabel(weekday: Int) -> String {
// TODO: Move this away, and reuse, it would be the same for every call ↓
var calendar = Calendar.autoupdatingCurrent
calendar.locale = Locale(identifier: "ru_RU") // Or any other locale, if you wan current, just drop this line
// TODO: ↑
return calendar.veryShortStandaloneWeekdaySymbols[weekday - 1] // because CalendarDateRangePickerViewController uses 1...7 weekday range, and here it's 0...6(or 0..<7)
}
And if you want weekdays described in more length use other *weekdaySymbols from the See Also section.
I am working on an app that has a startTime, endTime and duration. The user can set the endTime by click a button and it sets the value to "now" in the format 12:02:03 PM. I then want to be able to enter a duration time in minutes, let's say 20 minutes.
I have everything working where I can read the duration in real time as well as see the current time. The issue is when I try to create a function to subtract the duration from the endTime. I cannot seem to get the syntax or the formatting correct.
I've done quite a bit of searching for examples of this. Here is what I came across so far.
How to add minutes to current time in swift
How to subtract date components?
How to get the current time as datetime
func controlTextDidChange(_ obj: Notification) {
let enteredValue = obj.object as! NSTextField
timeString(time: enteredValue.doubleValue)
}
func timeString(time: TimeInterval) {
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let myString = formatter.string(from: Date())
let yourDate = formatter.date(from: myString)
formatter.dateFormat = "hh:mm:ss a"
yourDate!.addingTimeInterval(0-time)
let wtf = formatter.string(from: yourDate!)
startTime.stringValue = wtf
}
The controlTextDidChange function is watching the durationTextField and I am able to print to console the input. I then want to be able to run the timeString function with the durationTextField value and subtract it from the endTime and then set that value to startTime.
One thing that is weird is Xcode tells me:
Result of call to 'addingTimeInterval' is unused
You are taking too many steps. Just create a Date that is time seconds from "now". Then convert that Date to a String.
func timeString(time: TimeInterval) {
let startDate = Date(timeIntervalSinceNow: -time)
formatter.dateFormat = "hh:mm:ss a"
let wtf = formatter.string(from: startDate)
startTime.stringValue = wtf
}
I'm assuming you want startDate to be time seconds before now.
It's not weird, the warning tells you that addingTimeInterval creates and returns a new date.
Just do use the Result of call to 'addingTimeInterval'
The conversion Date to String and back to Date is pointless.
func timeString(time: TimeInterval) {
formatter.dateFormat = "hh:mm:ss a"
let newDate = Date().addingTimeInterval(-time)
let wtf = formatter.string(from:newDate)
startTime.stringValue = wtf
}
With the help of vadian and rmaddy I was able to make it work.
Here is my working code
func timeString(time: TimeInterval) {
formatter.dateFormat = "hh:mm a"
let endTimeValue = formatter.date(from: endTime.stringValue)
let newTime = endTimeValue!.addingTimeInterval(-time * 60)
let newtimeString = formatter.string(from:newTime)
startTime.stringValue = newtimeString
}
I have an API that returns data including a timestamp for that record.
In swift I have the timestamp element loaded and converted into a double and can then convert that into time. I want to be able to return the time if the date of the record is today and return the date if the record is not today.
See below:
let unixTimeString:Double = Double(rowData["Timestamp"] as! String)!
let date = NSDate(timeIntervalSince1970: unixTimeString) // This is on EST time and has not yet been localised.
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = .ShortStyle
dateFormatter.doesRelativeDateFormatting = true
// If the date is today then just display the time, if the date is not today display the date and change the text color to grey.
var stringTimestampResponse = dateFormatter.stringFromDate(date)
cell.timestampLabel.text = String(stringTimestampResponse)
Do I use NSCalendar to see if 'date' is today and then do something?
How do you then localise the time so that its correct for the user rather than server time?
There is a handy function on NSCalendar that tells you whether an NSDate is in today or not (requires at least iOS 8) isDateInToday()
To see it working, put this into a playground:
// Create a couple of unix dates.
let timeIntervalToday: NSTimeInterval = NSDate().timeIntervalSince1970
let timeIntervalLastYear: NSTimeInterval = 1438435830
// This is just to show what the dates are.
let now = NSDate(timeIntervalSince1970: timeIntervalToday)
let then = NSDate(timeIntervalSince1970: timeIntervalLastYear)
// This is the function to show a formatted date from the timestamp
func displayTimestamp(ts: Double) -> String {
let date = NSDate(timeIntervalSince1970: ts)
let formatter = NSDateFormatter()
formatter.timeZone = NSTimeZone.systemTimeZone()
if NSCalendar.currentCalendar().isDateInToday(date) {
formatter.dateStyle = .NoStyle
formatter.timeStyle = .ShortStyle
} else {
formatter.dateStyle = .ShortStyle
formatter.timeStyle = .NoStyle
}
return formatter.stringFromDate(date)
}
// This should just show the time.
displayTimestamp(timeIntervalToday)
// This should just show the date.
displayTimestamp(timeIntervalLastYear)
Or, if you just want to see what it looks like without running it yourself:
Abizern's answer in Swift 3:
import UIKit
let timeIntervalToday: TimeInterval = Date().timeIntervalSince1970
let timeIntervalLastYear: TimeInterval = 1438435830
// This is just to show what the dates are.
let now = Date(timeIntervalSince1970: timeIntervalToday)
let then = Date(timeIntervalSince1970: timeIntervalLastYear)
// This is the function to show a formatted date from the timestamp
func displayTimestamp(ts: Double) -> String {
let date = Date(timeIntervalSince1970: ts)
let formatter = DateFormatter()
//formatter.timeZone = NSTimeZone.system
if Calendar.current.isDateInToday(date) {
formatter.dateStyle = .none
formatter.timeStyle = .short
} else {
formatter.dateStyle = .short
formatter.timeStyle = .none
}
return formatter.string(from: date)
}
// This should just show the time.
displayTimestamp(ts: timeIntervalToday)
// This should just show the date.
displayTimestamp(ts: timeIntervalLastYear)
I'm having problems with NSDate in Swift.
I JSON a date formatted in Y-m-d from my database. This is stored as a string called survey_date
I then convert the string to a NSDate using dateFormatter
I want to work out the amount of days between the survey_date and NOW
Error in my script is endDate is ambiguous expression without more context.
Here is my script:
var survey_date = prefs.valueForKey("SURVEY_DATE") as! String
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var date = dateFormatter.dateFromString(survey_date) as NSDate!
let outputDate = dateFormatter.stringFromDate(date)
println(outputDate)
let start = outputDate
let end = NSDate()
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "yyyy-MM-dd"
let startDate:NSDate = dateFormatter2.dateFromString(start)!
let endDate:NSDate = dateFormatter2.dateFromString(end)!
let cal = NSCalendar.currentCalendar()
let unit:NSCalendarUnit = .CalendarUnitDay
let components = cal.components(unit, fromDate: startDate, toDate: endDate, options: nil)
println(components)
Secondly, I also want to be able to convert the date when possible to a different format - for example d m, Y. This is pretty simple to do in PHP but I can't find a way of doing it in Swift? I don't want to have to send extra data through JSON (i.e. create a $formatted_date) but it looks like this is my only option (which I know is messy and I will get told off for!)
You get a compiler error in
let endDate:NSDate = dateFormatter2.dateFromString(end)!
because dateFromString() is called with a date instead of a string,
which makes no sense.
Your computation is a bit too complicated, you can shorten it to
let survey_date = "2015-05-01"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let startDate = dateFormatter.dateFromString(survey_date) {
let endDate = NSDate()
let cal = NSCalendar.currentCalendar()
let components = cal.components(.CalendarUnitDay, fromDate: startDate, toDate: endDate, options: nil)
let days = components.day
println(days)
} else {
println("invalid input")
}
If you want to convert the date into a different format then
(as Leo already said in a comment), use stringFromDate() with
a second date formatter, e.g.
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "d MM, Y"
let formattedStartDate = dateFormatter2.stringFromDate(startDate)
println(formattedStartDate)
Here's something you may find handy. I was working on an app that did a lot of date calculations, and therefore was making lots of calls to NSCalendar's components(_:fromDate:toDate:options:) method. This doesn't feel terribly Swift-like, so I overloaded the - operator to do date subtractions:
func -(lhs: NSDate, rhs: NSDate) -> NSDateComponents
{
let components: NSCalendarUnit =
.CalendarUnitSecond |
.CalendarUnitMinute |
.CalendarUnitHour |
.CalendarUnitDay
return NSCalendar.currentCalendar().components(components,
fromDate: rhs,
toDate: lhs,
options: nil)
}
This lets you find the difference between any two dates/times by simple subtraction. Here's a quick example:
// MySQL date formatter
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// Let's create a couple of dates that we know are one day apart
let christmas2015 = dateFormatter.dateFromString("2015-12-25")!
let christmasEve2015 = dateFormatter.dateFromString("2015-12-24")!
let difference = christmas2015 - christmasEve2015
let daysBetween = difference.day // this value is 1