Creating NSDate from Int components - ios

I have a calendar with which I select a date:
func SACalendarDate(calendar: SACalendar!, didSelectDate day: Int32, month: Int32, year: Int32) {
var date = Date.from(year: Int(year), month: Int(month), day: Int(day))
print("\(year) and \(month) and \(day)")
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.MediumStyle
formatter.timeStyle = NSDateFormatterStyle.NoStyle
let dateString = formatter.stringFromDate(date)
buttonSelectDates.setTitle("\(dateString)", forState: UIControlState.Normal)
getUsers(date)
}
When I feed "date" in this method:
class func from(#year:Int, month:Int, day:Int) -> NSDate {
var c = NSDateComponents()
c.year = year
c.month = month
c.day = day
var gregorian = NSCalendar(identifier:NSCalendarIdentifierGregorian)
var date = gregorian!.dateFromComponents(c)
return date!
}
I get a date that is one day behind: selectedDate: 2015-07-14 22:00:00 +0000
And the parameters are: 2015, 7 and 15. Why does this happen?

NSDate is just a single point in time represented as seconds since 1.1.1970, it does not care about timezones or anything - its "timezone" is GMT and is +0000 (no offset). If you create a NSDate from a calendar with the local timezone, for example +0200 that timezone offset will be taken off the actual date you provide to represent a point in time without any timezone. To get a readable date representation of the NSDate back you need to use a NSDateFormatter which knows your current timezone:
let date = from(2015, month: 7, day: 15)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
print(dateFormatter.stringFromDate(date))
print(date)
You will receive the following printed output:
2015-07-15 00:00:00 +0200
2015-07-14 22:00:00 +0000

Related

Date Time change when convert to string issue

I'm trying to subtract minute from my date. BaseDate is my date and dateMinusMin is subtract is minuteFrom my date which work completely fine.
let baseDate = "2020-03-06 06:00" //My date With format "yyyy-MM-dd HH:mm"
let dateMinusMin = Calendar.current.date(byAdding: .minute, value: -(240), to: baseDate)!
print(dateMinus4Hours) \\2020-03-06 02:00:00 +0000
But when I convert Date to string time is change dramatically and showing 07:30 instead of 02:00.
let modifyStr = Utill.getLocalStringFromDate("yyyy-MM-dd HH:mm Z", date: dateMinus4Hours, iden: "en_US_POSIX")
print(modifyStr) \\ 2020-03-06 07:30 +0530
OutPut = 2020-03-06 07:30 +0530
Function to convert Date To string
func getLocalStringFromDate(_ currentFormat:String,date:Date,iden:String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = currentFormat
formatter.locale = Locale(identifier: iden)
return formatter.string(from: date)
}
I don't find any issue in your code. you can see result in below image.
Given Input - 06:00 hours
Output - 02:00 hours (4 hours minus as you want)

How to convert string Date to in milliseconds swift 3

I am getting date in this format "Thu Jul 20 06:44:40 +0000 2017" and I want to convert it in milliseconds so that I can compare this milliseconds to current date milliseconds.
I want to get 20 min difference from this date "Thu Jul 20 06:44:40 +0000 2017" to current date.
I want to check If 20 or less than 20 min difference is there then only I will do other operation.
I don't know how can I check 20 min difference.
//MiliSeconds from Date
func miliSecFromDate(date : String) -> String {
let strTime = date
let formatter = DateFormatter()
formatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
let ObjDate = formatter.date(from: strTime)
return (String(describing: ObjDate!.millisecondsSince1970))
}
Your date formatter is wrong.
Try using this:
let formatter = DateFormatter()
formatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
However you SHOULDN'T be comparing dates "in milliseconds".
The reason is that, when you convert it the time zone information is lost.
You should just compare Date instances directly since Swift supports it.
Check this answer to know how:
Swift 3 - Comparing Date objects
For compare to current time time less than or equal 20
Step 1:
Make Function which convert Given time to milli second Since Current Date and time.
func miliSecFromDate(date : String) -> TimeInterval {
let strTime = date
let formatter = DateFormatter()
formatter.dateFormat = "EEE MMM dd hh:mm:ss +zzzz yyyy"
let ObjDate = formatter.date(from: strTime)
return (ObjDate?.timeIntervalSinceNow)!
}
Step 2:
Now check Given time is less than or equal to 20 minute.
if miliSecFromDate(date: "Thu Jul 20 10:42:14 +0000 2017") >= -1200 {
print("less than 20 minute")
}else{
print("condition False")
}
Try this code:
func getMilliseconds(){
let strDate = "Thu Jul 20 06:44:40 +0000 2017"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE MMM DD hh:mm:ss +zzzz yyyy"
let date = dateFormatter.date(from: strDate)
print(date!)
let millieseconds = self.getDiffernce(toTime: date!)
print(millieseconds)
}
func getDiffernce(toTime:Date) -> Int{
let elapsed = NSDate().timeIntervalSince(toTime)
return Int(elapsed * 1000)
}

Date string to NSDate swift

i'm having an array fill with date string, which i would like to go through and check whether the date is today or yesterday. The date string could look like following:
2015-04-10 22:07:00
So far i've tried just to convert it using dateFormatter, but it keeps returning nil
var dateString = arrayNews[0][0].date as NSString
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
var date = dateFormatter.dateFromString(dateString as String)
println(date)
the sudo code i would like to look something like this
if dateString == currentDate
date = "Today, hh:mm"
else if dateString == currentDate(-1)
date = "Yesterday, hh:mm
else
date = dd. MM, hh:mm
in the else statement the date could be 1. April, 12:00
How can i achieve such a logic?
Without the logic
func getDate(dateStr:String, format:String = "yyyy-MM-dd HH:mm:ss") -> NSString {
var dateFmt = NSDateFormatter()
dateFmt.timeZone = NSTimeZone.defaultTimeZone()
dateFmt.dateFormat = format
let newsDate = dateFmt.dateFromString(dateStr)!
let date = NSDate();
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone()
let localDate = dateFormatter.stringFromDate(date)
return ""
}
You have to use yyyy-MM-dd HH:mm:ss instead of yyyy-MM-dd hh:mm:ss
HH: 24h format
hh: 12h format (with AM/PM)
Pay attention with dateFormatter, by default, it use localtime zone.
println() shows the value for GMT time, which is hold by NSDate.
It means, without specifying timezone, when you convert your string 2015-04-10 22:07:00 to NSDatetime, it return a data which is the time at your local time zone is 2015-04-10 22:07:00. As NSDate holds date time in GMT, you will see a different value when you show the value of that NSDate with println().
If your timezone is GMT+2 (2h earlier than GMT), when it's 22h:07 in your place, the GMT time is 20h:07. When you call println() on that NSDate, you see 2015-04-10 20:07:00
To compare 2 NSDate:
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)
let compareResult = calendar?.compareDate(date, toDate: date2, toUnitGranularity: NSCalendarUnit.CalendarUnitDay)
if (compareResult == NSComparisonResult.OrderedSame) {
println("yes")
} else {
println("no")
}
//to get yesterday, using NSCalendar:
let yesterday = calendar?.dateByAddingUnit(NSCalendarUnit.CalendarUnitDay, value: -1, toDate: date, options: NSCalendarOptions.MatchStrictly)

Why can I not format my NSDate with the specified time zone with NSDateFormatter?

I want to get a date that is represented in a String with a time zone GMT+1 and display it on screen with the local time zone GMT+10.
I have 2 methods, one is for create a date from a String (with GMT+1 timeZone), the other one is to format the date into a String (with localTimeZone GMT+10):
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+1")
dateFormatter.dateFormat = "M/d/yyyy hh:mma"
return dateFormatter.dateFromString(dateString)
}
func stringFromDate(date: NSDate) -> String {
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
return dateFormatter.stringFromDate(date)
}
In the playground, when I do this:
let date = dateFromString("4/8/2015 1:29am")!
println(date)
println(stringFromDate(date))
I get the following output on the right side:
"Apr 8, 2015, 1:29 AM"
"2015-04-07 15:29:00 +0000"
"1:29 AM"
I don't understand why I don't get what I am expecting and looking for:
"Apr 8, 2015, 1:29 AM"
"2015-04-08 10:29:00 +0000"
"10:29 AM"
What's wrong?
Input formatters need the time zone in their string. Like so:
func dateFromString(dateString: String) -> NSDate? {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "M/d/yyyy hh:mma z"
return dateFormatter.dateFromString(dateString)
}
let date = dateFromString("4/8/2015 1:29am GMT+01")!
Also note that NSTimeZone names have a two digit offset. Compare in the playground
var oops = NSTimeZone(abbreviation: "GMT+1")
var righteous = NSTimeZone(abbreviation: "GMT+01")
The first is nil, the second is not.
I wouldn't trust the formatting of a time stamp that the debugger prints. In my experience dates are always in UTC regardless of the time zone you set according to the log. Try adding the date as a string to a label on the project and see if it's right.
The reasoning behind this as far as I know is that when you print to the log, all it's doing is calling -description. In the case of NSDate this will return in UTC by definition.

How to extract day, month and year (dd-MM-yyyy) from Date (2018-09-28 09:42:00 +0000 ) without time in Date format - iOS swift?

I want to get 2018-09-28 from 2018-09-28 09:42:00 +0000 in Date format. I
can extract the same in string format but I want to get this in Date format. Here is my sample code.
let date = Date(timeIntervalSince1970: (TimeInterval(timer/1000)))
let df = DateFormatter()
df.dateFormat = "yyyy-MM-dd"
let myDate = df.string(from: date)
let updateDate = df.date(from: myDate)
//date - 2018-09-28
//updateDate - 2018-09-28 09:42:00 +0000
You can simply get your date string prefix 11 and insert noon time when parsing your string:
let str = "2018-09-28 09:42:00 +0000"
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "yyyy-MM-dd HH:mm"
if let date = df.date(from: str.prefix(11) + "12:00") {
print(date.description(with: .current))
}
// Friday, September 28, 2018 at 12:00:00 PM Brasilia Standard Time

Resources