Show Date with DateFormatter - swift

I'm looking for a way to display the current date in a label with Swift 3.
Currently I'm using DateFormatter.dateFormat but the only output I get is
dd.MM.yyyy
Here is the line of code:
lbl_Date.text = DateFormatter.dateFormat(fromTemplate: "MMddyyyy", options: 0, locale: NSLocale(localeIdentifier: "de-AT") as Locale)
And my expected output for today should be:
11.12.2016
I know that I can get the time with the dateTimeComponents but I haven't figured out how I can get only the date (day, month and year) in my label:
// get the current date and time
let currentDateTime = Date()
// get the user's calendar
let userCalendar = Calendar.current
// choose which date and time components are needed
let requestedComponents: Set<Calendar.Component> = [
.year,
.month,
.day,
.hour,
.minute,
.second
]
// get the components
let dateTimeComponents = userCalendar.dateComponents(requestedComponents, from: currentDateTime)
What is there the cleanest way to display the current date in my label?

Forget Calendar and DateComponents. Use DateFormatter
let currentDateTime = Date()
let formatter = DateFormatter()
If you want a fixed format set the dateFormat to
formatter.dateFormat = "dd.MM.yyyy"
alternatively if you want a format depending on the current locale set timeStyle and dateStyle rather than the format property
formatter.timeStyle = .none
formatter.dateStyle = .medium
Now get the string
let dateString = formatter.string(from: currentDateTime)

Related

Date not convert in AM/PM Format in swift

I need to date and time with my own format like time in AM/PM (12 hours).
extension Date {
func getStringFromDateWithUTCFormat() -> ObjTimeStamp {
let dateFormatterPrint = DateFormatter()
dateFormatterPrint.timeZone = TimeZone.init(abbreviation: "UTC")
// Get Date
dateFormatterPrint.dateFormat = "MM/dd/yyyy" //"MMM dd,yyyy"
let date = dateFormatterPrint.string(from: self)
// Get Time
dateFormatterPrint.dateFormat = "hh:mm:ss a"
let time = dateFormatterPrint.string(from: self)
return ObjTimeStamp.init(date: date, time: time, timeStamp: self)
}
}
Update
Calling function
self.currentDate = Date()
let objTimeStamp = currentDate.getStringFromDateWithUTCFormat()
Perfect work when device time in 12-hour format when I try to change device time in 24-hour formate then given wrong time format.
set your dateFormatter locale to en-US then try to convert, it's works for me when iPhone's time format is 24 hour:
let date = Date()
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en-US")
formatter.dateFormat = "hh:mm a"
let time12 = formatter.string(from: date)
print(time12)
output:
01:37 PM

ISO8601DateFormatter in swift lost nanoseconds

I'm trying to parse date with folloing code:
let dateFormatter = ISO8601DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "UTC")
dateFormatter.formatOptions = [ .withInternetDateTime, .withFractionalSeconds ]
let date = dateFormatter.date(from: "2019-01-30T23:51:55.650144Z")
let string = dateFormatter.string(from: date) // 2019-01-30T23:51:55.650Z
Input date:
2019-01-30T23:51:55.650144Z
But output date is:
2019-01-30T23:51:55.650Z
This is keep only 3 digits in fractional part.
How to avoid it?

Swift 3.0 Converting String to Date

I'm trying to convert String date to local timeZone date then convert it back to Date with my current timeZone first method is working well:
let date = convertToLocalTimeZone(dateStr:"2018-05-30T14:13:20.000Z")
print(date)
the following is printed which is right:
2018-05-30 16:13GMT+2
let newDate = convertStringToDate(dateStr:date)
print(newDate)
//Converted back to UTC Time Zone :(
2018-05-30 14:13:00 +0000
func convertToLocalTimeZone(dateStr:String)->String{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:sss.SSSZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let date = dateFormatter.date (from: dateStr)
dateFormatter.timeZone = TimeZone(secondsFromGMT: getSecondsFromGMT())
dateFormatter.dateFormat = "yyyy-MM-dd HH:mmz"
let strVal = dateFormatter.string(from: date!)
return strVal
}
The problem happens when i try to convert the new String date with my local timeZone to date it returns wrong timeZone:
func convertStringToDate(dateStr:String)->Date{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mmz"
// dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2")
let date = dateFormatter.date (from: dateStr)
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day, .hour], from: date!)
let finalDate = calendar.date(from:components)
return finalDate!
}
Any Help will be much appreciated
I think your code is alright. You just have to understand that Date represents a point in time. It does not know anything about time zones. Time zones appears only when you format the date, so only in a String will you ever see a time zone. No matter how you create a Date, you are going to see it end up in UTC when it is printed directly.
So if you want to show a date in a time zone, format it, just like you did in convertToLocalTimeZone.
If you want, you could create your own date with a Date and a TimeZone:
struct ZonedDate: CustomStringConvertible {
var date: Date
var timeZone: TimeZone
var description: String {
// format the date using timeZone here...
}
}

How to get Int from DateFormatter() in Swift3

I want to remove some data from my UITableView when the data is passed over 24 hours. I saved date as String. I want to check the date but because it is String, how am I able to turn that data into Int value in order to check how many hours have passed since the data is last entered? Is there any good code for that to happen? This date data is stored in Firebase.
let currentDateTime = Date()
let formatter = DateFormatter()
formatter.timeStyle = .medium
formatter.dateStyle = .long
let date = formatter.string(from: currentDateTime)
You need:
Your date
Add 24 hours to that date
Compare that new date with "now"
I am assuming you have some date already:
let myDate: Date = ...
Let's add 24 hours:
let endDate: Date = Calendar.current.date(byAdding: .hour, value: 24, to: myDate, wrappingComponents: true)!
Did 24 hours already passed since my date?
let now = Date()
let expired = (endDate < now)
I am not sure why would you even use a date formatter for this task.
Try this:
let currentDateTime = Date()
let formatter = DateFormatter()
formatter.dateFormat = "hh"
let date = formatter.string(from: currentDateTime)
print(date)// Time in string
print(Int(date)!) // Time in Int

How can i divide NSDate() into pieces?

func date() -> String {
return NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.MediumStyle)
}
var date = date() // 2016. 5. 13. 오전 4:45:16
above code, date obtain korean current value of date every time that i call date()
I'll hope to have refresh new value from NSDate(), and so insert refresh new value into varibles like below code
var yearMonDay = "2016. 5. 13"
var hourMinSec = "오전 4:45:16"
hmmm Are there methods to divide NSDate() into pieces like below code?
yearMonDay = NSDate().?? // refresh date "year: month: day"
hourMinSec = NSDate().?? // refresh date "am/fm hour:minute:second
Splitting up components like hour can be done using the components of the NSCalendar
let today = NSDate()
let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: today)
print("\(components.month) \(components.day) \(components.year)")
print("\(components.hour) \(components.minute) \(components.second)")
With the NSDate formatter you can find the names
let formatter = NSDateFormatter()
let monthName = formatter.monthSymbols[components.month-1]
print(monthName)
You can use the NSDateFormatterStyle:
// get the current date and time
let currentDateTime = NSDate()
// initialize the date formatter and set the style
let formatter = NSDateFormatter()
// October 26, 2015
formatter.timeStyle = NSDateFormatterStyle.NoStyle
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.stringFromDate(currentDateTime)
// 6:00:50 PM
formatter.timeStyle = NSDateFormatterStyle.MediumStyle
formatter.dateStyle = NSDateFormatterStyle.NoStyle
formatter.stringFromDate(currentDateTime)