How can i achieve this kind of format?? using "NSDateFormatter"
March 1-2 2016?
Is there a format to get day only, Month only, Year only?
let dateString = self.dateLists[indexPath.row]
let dateFormatter2 = NSDateFormatter()
dateFormatter2.dateFormat = "MMMM"
let date2 = dateFormatter2.dateFromString(dateString as String)
You need the correct dateformat to get everything you want from an Datestring.
If your date is a string, you need to convert it first to an NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // the format of your string
dateFormatter.timeZone = NSTimeZone(name: "GMT")
if let date = dateFormatter.dateFromString(dateString) {
// conversation to NSDate() was successful
// now convert to anything you want
dateFormatter.dateFormat = "MMMM"
let newDateString = dateFormatter.stringFromDate(date)
}
Here are all available Dateformatters, for example:
Month only (as text):
“MMMM”
Or as 2 digit String:
“MM”
Here is all you need:
http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
let str1 = "May 12 1968 04:00 PM"
let str2 = "May"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "MM"
let date1 = dateFormatter.dateFromString(str1) // nil
let date2 = dateFormatter.dateFromString(str2) // May 1, 2000, 12:00 AM
dateFormatter.dateFormat = "MM dd yyyy hh:mm a"
let date3 = dateFormatter.dateFromString(str1) // May 12, 1968, 04:00 PM
let date4 = dateFormatter.dateFromString(str2) // nil
check your input string ... it must conform to you format
check your locale, even though you define your custom format, the
system use the locale (gregorian vs julian calendar ... etc)
if it still doesn't work, parse you string 'manually'
Related
I have strings and converting into the date format, but when I convert after the date is showing properly but time is showing the wrong format
firsDateString : 2019-Mar-15 9:00 AM
secondName : 2019-Mar-15 8:00 PM
String convert into the date format
let addedDate = firsDateString
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")
After that am getting this values:
DATE Optional(2019-03-15 03:30:00 +0000)
How can get the correct date format?
use like , but is not a valid answer may be it works based on your condition but follow option2 it will cover all scenario if you need
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
let date1 = formatter.date(from: "2019-Mar-15 9:00 AM")
formatter.amSymbol = ""
formatter.pmSymbol = ""
let currentDateStr = formatter.string(from: date1!)
print("currentDateStr (currentDateStr)")
based on #JoakimDanielson point
How can this be the accepted answer when you no longer can tell the difference between 8 in the morning and 8 in the evening
here you need to follow the 24 hour format , I update my answer ,
Option 2
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
let date1 = formatter.date(from: "2019-Mar-15 9:00 AM")
formatter.dateFormat = "yyyy-MMM-dd HH:mm"
let currentDateStr = formatter.string(from: date1!)
print("currentDateStr \(currentDateStr)")
Output
Check this:
let addedDate = firsDateString
let formatter = DateFormatter()
formatter.timeZone = (NSTimeZone(name: "UTC")! as TimeZone)
formatter.dateFormat = "yyyy-MMM-dd hh:mm a"
let date1 = formatter.date(from: addedDate)
print("DATE \(String(describing: date1!))")
I want to set "EST" as the default time zone for every user, but there is one condition that needs to be check in the current date at 7:45 PM. So I am comparing two dates, but the problem is when I convert the current Date to String it gives me the correct EST time, when I convert that String again to Date in EST it gives me time 4 hours ahead of EST. Here is the code for conversion
class func getCurrentDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
print(dateString)
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDate = convertDateFormatter.string(from: Date())
print(currentDate)
let comparedDateFormatter = DateFormatter()
comparedDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
comparedDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let comparedDate = comparedDateFormatter.date(from: "\(currentDate) 19:45:00")
print(comparedDate)
let currentDateFormatter = DateFormatter()
currentDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
comparedDateFormatter.timeZone = TimeZone.init(abbreviation: "EST")
let currentDateAndTime = currentDateFormatter.date(from: dateString)
print(currentDateAndTime)
return dateString
}
So a date does not have a time zone.
So when I use a dateFormatter to convert a date to a string representation of the string will reflect the time zone the dateFormatter is set to.
But when you use the same formatter to convert the the string back into a date the date would not have the the time zone offset anymore.
So this sounds to me as if it is working properly.
Edit:
So if you are trying to compare two dates I would do something like:
let date1 = Date()
let date2 = Date().addingTimeInterval(100)
if date1 == date2 {
// dates are exactly equal
} else if date1 > date2 {
// date1 is the most recent
} else if date1 < date2 {
// date2 is the most recent
}
And if I were trying to display these dates I would use the date formatter to convert them to strings.
I modified the code as you requested:
func getCurrentDateTime() -> String {
var checkString : String!
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss a"
let dateString:String! = dateFormatter.string(from: Date())
let dateFormatter1 = DateFormatter()
dateFormatter1.timeZone = TimeZone(abbreviation: "EST")
dateFormatter1.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString1:String! = dateFormatter1.string(from: Date())
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDateformat = convertDateFormatter.string(from: Date())
let compareDate = "\(currentDateformat) 07:45:00 PM"
let compareDate1 = "\(currentDateformat) 07:45:00"
if dateString == compareDate {
checkString = "equal date"
}
if dateString1 < compareDate1{
checkString = "greater than"
} else {
checkString = "less than"
}
return checkString
}
func getCurrentDateTime() -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(abbreviation: "EST")
dateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let dateString = dateFormatter.string(from: Date())
let convertDateFormatter = DateFormatter()
convertDateFormatter.dateFormat = "dd-MM-yyyy"
convertDateFormatter.timeZone = TimeZone(abbreviation: "EST")
let currentDate = convertDateFormatter.string(from: Date())
let comparedDateFormatter = DateFormatter()
comparedDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let comparedDate = comparedDateFormatter.date(from: "\(currentDate) 19:45:00")
let currentDateFormatter = DateFormatter()
currentDateFormatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
let currentDateAndTime = currentDateFormatter.date(from: dateString)
return dateString
}
Plesae check this code .
Actually I didn't find anything wrong with the code.
The Date always be in UTC timezone. The DateFormatter did the magic.
To print Date in as per the format:
use string(from:) method.
if let currentDateAndTime = currentDateFormatter.date(from: dateString) {
print(currentDateFormatter.string(from: currentDateAndTime))
}
NB: When working with fixed format dates, such as RFC 3339, you set
the dateFormat property to specify a format string. For most fixed
formats, you should also set the locale property to a POSIX locale
("en_US_POSIX"), and set the timeZone property to UTC.
I am getting date string from server like that "2017-08-05T00:30:00.000+02:00". Below is my code for date formatter.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
But it returns 2017-08-04 22:30:00 +0000. Which is wrong. Any suggestions?
In Swift 3
You can change your server time string to UTC time Date as:
let dateFormatter: DateFormatter = DateFormatter()
var serverDateString = "2017-08-05T00:30:00.000+02:00"
let index = serverDateString.index(serverDateString.startIndex, offsetBy: 19)
serverDateString = serverDateString.substring(to: index)
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.init(identifier: "UTC")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Your Code for parsing date is correct: 2017-08-05T00:30:00.000+02:00 and 2017-08-04 22:30:00 +0000 represent the same time, just in different time zones. Your only problem is that Date doesn't actually store the time zone
yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ
This is correct date formate for your input string. Here is the Apple Document for more description.
Here is my code:
var strInputDateString: String = "2017-08-05T00:30:00.000+02:00"
var dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy-MM-dd'T'hh:mm:ss.SSSZZZZZZ"
//Set new dateFormate
var date1: Date? = dateFormat.date(from: strInputDateString)
dateFormat.dateFormat = "dd-MM-YYYY hh:mm:ss"
// Your Desire
var strOutputDateString: String = dateFormat.string(from: date1!)
print("\(strInputDateString)")
print("\(strOutputDateString)")
output:
Main input String:2017-08-05T00:30:00.000+02:00
Converted String: 05-08-2017 04:00:00
For now, I tried to convert your date format with my custom. It's give me the perfect output.
Actually, your code is good.
I copied your data and ran it in playground.
What kind of format you want it be?
Try this
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXX"
dateFormatter.locale = Foundation.Locale(identifier: "en_US_POSIX")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
Hope this helps
The step you are missing is to again use your DateFormatter to format the date into a string. When you use print on the date, it will always show GMT. For illustration purposes, I've set the TimeZone to Berlin to match the original offset of +2:00.
let dateFormatter: DateFormatter = DateFormatter()
let serverDateString = "2017-08-05T00:30:00.000+02:00"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZZ"
// Hard set to Berlin
dateFormatter.timeZone = TimeZone(identifier: "Europe/Berlin")
let currentDate: Date = dateFormatter.date(from: serverDateString)!
// Your missing step
dateFormatter.string(from: currentDate)
Remember that DateFormatters are about:
Parsing from a String - df.date(from: String)
Formatting from a Date - df.string(from: Date)
I have a string that is a date in this format 03/02/2017
I would like to display it like this Mar 2, 2017
I've been trying to get this formatter to work, but it keeps giving me nil, and I don't think I'm setting it in the correct format.
// convert saved date from string
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "mm/dd/yyyy" //Your date format
let date = dateFormatter.date(from: '03/02/2017')
print("\(date) save date") // nil
historyEntry.date = date as NSDate?
is not in
dateFormatter.dateFormat = "mm/dd/yyyy"
it is in
dateFormatter.dateFormat = "MM/dd/yyyy"
for full output
let dateFormatter = DateFormatter()
// iinitiallly set the date format based on your date
dateFormatter.dateFormat = "MM/dd/yyyy" //Your date format
// convert the string to date , but date is not the proper format , so dont worry about this
let date = dateFormatter.date(from: "03/02/2017")
// again reassign what the output you need set the date format
dateFormatter.dateFormat = "MMM dd, yyyy" // if you need the same as Mar 2, 2017 then use "MMM d, yyyy"
// finally convert your date to string
let myStringafd = dateFormatter.string(from: date!)
print("\(myStringafd) save date")
output
let dateString = "03/02/2017"
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy" // this dateformat should be your current string's date format
df.timeZone = TimeZone(identifier: "UTC-05:00") // if there is timezone you want to set
if let date = df.date(from: dateString) {
df.dateFormat = "MMM dd, yyyy" // This dateformat is that you want as result
let stringFromDate = df.string(from: date)
cell.lblDate.text = stringFromDate
}
From response I have set time in String, its contains HH: mm format the task is I have to convert that string into 12hrs time interval with AM and PM in another string to display results
For example "16:36:00.000Z" I want my result like 4:36 PM
Here my sample code:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let date = dateFormatter.dateFromString(dateValue)
// To convert the date into an HH:mm format
dateFormatter.dateFormat = "HH:mm"
let dateString = dateFormatter.stringFromDate(date!)
print(dateString)
But unfortunately I'm getting nil in date
do like
let dateFormatter = NSDateFormatter()
16:36:00.000Z
dateFormatter.dateFormat = "HH:mm:ss.sssZ"
let date = dateFormatter.dateFromString(dateValue)
// To convert the date into an HH:mm format
dateFormatter.dateFormat = "hh:mm a" // or //h:mm a
let dateString = dateFormatter.stringFromDate(date!)
print(dateString)