how to work with UIDatePicker in Swift? - ios

I built a UI that has 3 UIDatePicker
The first UIDatePicker named date will be for Date only (Mode .Date)
Other UIDatePickers names time_from and time_to will be for Time (From time, To time) (Mode .Time)
Then I add a Button,
When I click the button I need to get two variables:
From_DateTime and To_DateTime
(I need the Date from date UI and the time from time_from, time_to
I try a lot but without the desired result:
let date = date.calendar
let date_components = date.components(.Calendar, fromDate: date.date)
let date_from_components = dateFrom.calendar.components(.Calendar, fromDate: dateFrom.date)
let date_to_components = dateTo.calendar.components(.Calendar, fromDate: dateTo.date)
let n = date.calendar.dateBySettingHour(date_from_components.hour, minute: date_from_components.minute, second: 5, ofDate: dateFrom.date, options: NSCalendarOptions.MatchStrictly)
This is an example of fails trying.
I need a simple way to get From_DateTime and To_DateTime
Thanks

Finally I found a way:
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "US")
dateFormatter.dateFormat = "yyyy-MM-dd"
let timeFormatter = NSDateFormatter()
timeFormatter.locale = NSLocale(localeIdentifier: "US")
timeFormatter.dateFormat = " HH:mm"
let date_from = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateFrom.date)
let date_to = dateFormatter.stringFromDate(date.date) + timeFormatter.stringFromDate(dateTo.date)
I am sure there must be another simple way.

Related

Swift4: Calendar gives me wrong value for secondsFromGMT

For my iOS App I need some calculations for Dates and Time. By using the class Calendar I found out, that this class gives me some wrong values for dates in the 19th century and before. During this time, the time zones in Europe were very unstructured. For example, GMT+0:53:28. The class Calendar knows about this and shows me the correct time zone. But the return value of "secondsFromGMT" is wrong: 3600 seconds in this case. Does anyone have some experience with this error or with related problems?
import Foundation
let timeZone = TimeZone(identifier: "Europe/Berlin")
var calendar = Calendar.current
calendar.timeZone = timeZone!
let formatter = DateFormatter()
formatter.dateFormat = "dd.MM.yyyy HH:mm:ss"
formatter.locale = Locale(identifier: "en-US")
let date = formatter.date(from: "01.07.1622 08:10:00")!
formatter.dateStyle = .long
formatter.timeStyle = .long
let stringDate = formatter.string(from: date)
let offsetFromGMT = calendar.timeZone.secondsFromGMT(for: date)
print(stringDate, " Offset =", offsetFromGMT)
July 1, 1622 at 8:10:00 AM GMT+0:53:28 Offset = 3600

How to add minutes to custom time in swift2

What I do is:
How to add minutes to current time in swift
how to add 30 minutes to current time
Here is my code:
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
endTime?.dateByAddingTimeInterval(180) // 3 Minute
print(endTime)
1st answer #rob i tried that one but failed . second answer suggest dateByAddingTimeInterval i am not suer is it is work or not .
You need to use dateByAddingUnit as #Rob doing instead of dateByAddingTimeInterval. The reason you are not getting correct time is may because of TimeZone so try to set timeZone with your NSDateFormatter instance.
endFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
endFormatter.timeZone = NSTimeZone(abbreviation: "UTC")
let endTimeString = "2017-01-16 12:58:56"
let endTime = endFormatter.dateFromString(endTimeString)
//Now add the 3 minute in endTime
let calendar = NSCalendar.currentCalendar()
let date = calendar.dateByAddingUnit(.Minute, value: 3, toDate: endTime, options: [])
let dateWithMinuteInterval = Calendar.current.date(byAdding: DateComponents(minute: 23), to: endTime)!

NSDate from string is always nil

I receive dates as String like this one:
"2016-05-20T12:25:00.0"
I want to get its corresponding NSDate object, and I'm trying this way:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)
where dateStr is like the example I wrote first. I took the dateFormat string from this page, but I get a nil date, what is wrong there?
Thanks in advance
You have a few problems with your date format. First Y is for weekOfYear, D is for day of year. hh is used for 12 hours format, decimal second you should use capital S and you need to escape the 'T'
You should do as follow:
let dateString = "2016-05-20T12:25:00.0"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.dateFromString(dateString) {
print(dateFormatter.stringFromDate(date) ) // "2016-05-20T12:25:00.0\n"
}
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
print(dateFormatter.stringFromDate(date) )
}

Hijri (islamic) calendar in swift التاريخ الهجري

can someone help me please
I'm trying to create an IOS app using Swift language and I need to use Hijri (islamic) calendar
I tried many time but I failed :(
this is my try
let datenow = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit(UInt.max), fromDate: datenow)
var gregorian = NSCalendar(identifier:NSIslamicCivilCalendar)
var date = gregorian.dateFromComponents(components)
println(date)
and the output is wrong
2576-04-25 09:05:08 +0000
We are in year 1434 in hijri not 2576 !
You're mixing up the calendars, dates & components:
let datenow = NSDate()
// This is a point in time, independent of calendars
let calendar = NSCalendar.currentCalendar()
// System calendar, likely Gregorian
let components = calendar.components(NSCalendarUnit(UInt.max), fromDate: datenow)
// Gregorian components
println("\(components.year)") // "2014"
var islamic = NSCalendar(identifier:NSIslamicCivilCalendar)! // Changed the variable name
// *** Note also NSCalendar(identifier:) now returns now returns an optional ***
var date = islamic.dateFromComponents(components)
// so you have asked to initialise the date as AH 2014
println(date)
// This is a point in time again, sometime in AH 2014, or AD 2576
What you need to do is simply:
let datenow = NSDate()
let islamic = NSCalendar(identifier:NSIslamicCivilCalendar)!
let components = islamic.components(NSCalendarUnit(UInt.max), fromDate: datenow)
println("Date in system calendar:\(datenow), in Hijri:\(components.year)-\(components.month)-\(components.day)")
//"Date in system calendar:2014-09-25 09:53:00 +0000, in Hijri:1435-11-30"
To get a formatted string, rather than just the integer components, you need to use NSDateFormatter, which will allow you to specify the calendar & date as well as the format. See here.
Update
To simply transliterate the numerals to (Eastern) Arabic numerals (as 0...9 are referred to as (Western) Arabic numerals to distinguish them from, say, Roman numerals), as requested, you could use:
let sWesternArabic = "\(components.day)-\(components.month)-\(components.year)"
let substituteEasternArabic = ["0":"٠", "1":"١", "2":"٢", "3":"٣", "4":"٤", "5":"٥", "6":"٦", "7":"٧", "8":"٨", "9":"٩"]
var sEasternArabic = ""
for i in sWesternArabic {
if let subs = substituteEasternArabic[String(i)] { // String(i) needed as i is a character
sEasternArabic += subs
} else {
sEasternArabic += String(i)
}
}
println("Western Arabic numerals = \(sWesternArabic), Eastern Arabic numerals = \(sEasternArabic)")
Get Hajri Date:
Swift :
let dateFor = DateFormatter()
let hijriCalendar = Calendar.init(identifier: Calendar.Identifier.islamicCivil)
dateFor.locale = Locale.init(identifier: "ar") // or "en" as you want to show numbers
dateFor.calendar = hijriCalendar
dateFor.dateFormat = "dd/MM/yyyy"
print(dateFor.string(from: Date()))
Obj-C :
NSCalendar *hijriCalendar2 = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierIslamicCivil];
NSDateFormatter * lastDate = [[NSDateFormatter alloc]init];
lastDate.calendar = hijriCalendar2;
[lastDate setDateFormat:#"dd/MM/yyyy HH:mm:ss"];
NSString * dateString = [lastDate stringFromDate:[NSDate date]];
thank you #Grimxn and I also find a great way to show arabic numbers
let formatter = NSNumberFormatter()
formatter.locale = NSLocale(localeIdentifier: "ar_SA")
var date:String = "\(formatter.stringFromNumber(components.year))-\(formatter.stringFromNumber(components.month))-\(formatter.stringFromNumber(components.day))"
it will print ١-١١-١٤٣٤
Swift 3 & 4
let dateNow = DateFormatter()
let islamicCalendar = Calendar.init(identifier: Calendar.Identifier.islamicCivil)
dateNow.calendar = islamicCalendar
dateNow.locale = Locale.init(identifier: "ar_SA") // This is used to show numbers, day and month in arabic letters
dateNow.dateFormat = "EEE dd MMM yyyy"
print("\(dateNow.string(from: Date()))")
find out and place date format from:
http://userguide.icu-project.org/formatparse/datetime
Swift 5:
let hijriCalendar = Calendar(identifier: .islamicCivil)
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "ar")
formatter.calendar = hijriCalendar
formatter.dateFormat = "dd/MM/yyyy"
print(formatter.string(from: Date()))

How to display date with human language like "Today at xx:xx pm", "Yesterday at xx:xx am"?

I have a date "2014-07-02 20:57:38 +0000" and I want to format it as "Today at 8:57 pm".
I want that if a string is yesterday, then display it as "Yesterday at 9:00 am". If it is neither today or yesterday, just show the actually date like "27/6 at 7:53 pm".
I was able to get the time with format like "8:57 AM" with the code below.
var formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
// message.createdAt is the date
let dateString = formatter.stringFromDate(message.createdAt)
println(dateString)
//output = 8:57 AM
However, when I use the following code, it returns a blank string.
var formatter : NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "h:mm a"
formatter.doesRelativeDateFormatting = true //<-- This doesn't work
let dateString = formatter.stringFromDate(message.createdAt)
println(dateString)
//output = (nothing, its a blank string)
How do I make this work and display "Today" or "Yesterday" in Swift?
The reason it's blank is that your date format only has time components. Combined with .doesRelativeDateFormatting that gives you the empty string. If you want that custom time format, I think you need separate formatters for the date and the time:
let now = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.doesRelativeDateFormatting = true
let timeFormatter = NSDateFormatter()
timeFormatter.dateFormat = "h:mm a"
let time = "\(dateFormatter.stringFromDate(now)), \(timeFormatter.stringFromDate(now))"
println(time) // prints "Today, 5:10 PM"
With Swift 5.1, Apple Developer API Reference states about DateFormatter's dateFormat property:
You should only set this property when working with fixed format representations, as discussed in Working With Fixed Format Date Representations. For user-visible representations, you should use the dateStyle and timeStyle properties, or the setLocalizedDateFormatFromTemplate(_:) method if your desired format cannot be achieved using the predefined styles; both of these properties and this method provide a localized date representation appropriate for display to the user.
The following Playground sample code shows how to display your dates in the desired format using dateStyle, timeStyle and doesRelativeDateFormatting properties:
import Foundation
let now = Date() // 2019-08-09 12:25:12 +0000
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: now)! // 2019-08-08 12:25:12 +0000
let aWeekAgo = Calendar.current.date(byAdding: .weekOfMonth, value: -1, to: now)! // 2019-08-02 12:25:12 +0000
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true
let nowString = dateFormatter.string(from: now)
print(nowString) // prints: Today at 2:25 PM
let yesterdayString = dateFormatter.string(from: yesterday)
print(yesterdayString) // prints: Yesterday at 2:25 PM
let aWeekAgoString = dateFormatter.string(from: aWeekAgo)
print(aWeekAgoString) // prints: August 2, 2019 at 2:25 PM
Give this a try in Swift:
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .short
dateFormatter.doesRelativeDateFormatting = true
let date = Date()
let dateString = dateFormatter.string(from:date)

Resources