How to get Date, Month and Year into Millisecond in swift - ios

Hi am Trying to convert year, month date into Millisecond how to do please help me to do this,
Bellow Is my Code that i have try.
let date:String = "2018-08-04T07:34:15.287Z"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateFromString = Date()
if let aString = dateFormatter.date(from: date) {
dateFromString = aString
}
let timeInMiliseconds:Int = Int(TimeInterval(dateFromString.timeIntervalSince1970 * 1000))
return timeInMiliseconds
But I Alway Got DateTime Into Millisecond.
when I am trying to get the only date into millisecond please help I need help.
Thanks in advance.

Your dateFormat is not match with date. Try below code:
let date:String = "2018-08-04T07:34:15.287Z"
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let dateToConvert = dateFormatter.date(from: date)
dateFormatter.dateFormat = "yyyy-MM-dd"
let finalDate = dateFormatter.string(from: dateToConvert!)
var dateFromString = Date()
if let aString = dateFormatter.date(from: finalDate) {
dateFromString = aString
}
let timeInMiliseconds:Int = Int(TimeInterval(dateFromString.timeIntervalSince1970 * 1000))
You will get 1533321000000 in timeInMiliseconds
You can check time here

Related

Date from String is not giving correct date

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.

How to get time from YYYY-MM-dd'T'HH:mm:ss.sssZ

Hi I want to get time as 11:40 from 2017-07-31T11:40:00.000Z
Below is the code I am using:
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: data.arvTime)
print("date:\(String(describing: date1))")
let dateFormatterPrint = Foundation.DateFormatter()
dateFormatterPrint.dateFormat = "HH:mm"
let resultTime = dateFormatterPrint.string(from: date1!)
print("time:\(String(describing: resultTime))")
Getting time as 1:29 i.e. I am getting wrong time.
Please help me to solve this issue.
use the dateformat
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
instead of
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ"
for full code
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: "2017-04-01T18:05:00.000Z")
print("date:\(String(describing: date1))")
formatter.dateFormat = "HH:mm"
let resultTime = formatter.string(from: date1!)
print("time:\(String(describing: resultTime))")
option-2
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.sssZ" //2017-04-01T18:05:00.000
let date1 = formatter.date(from: "2017-04-01T18:05:00.000Z")
print("date:\(String(describing: date1))")
formatter.timeZone = TimeZone(abbreviation: "UTC")
formatter.dateFormat = "HH:mm"
let resultTime = formatter.string(from: date1!)
print("time:\(String(describing: resultTime))")
output
NSLog always prints the date object in GMT timezone, not your local timezone. use your local time zone
Try this
Use the timeZone property of the dateFormatter.
let formatter = Foundation.DateFormatter()
formatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss.sssZ"
let date1 = formatter.date(from: "2017-07-31T11:40:00.000Z")
print("date:\(String(describing: date1))")
let dateFormatterPrint = Foundation.DateFormatter()
dateFormatterPrint.timeZone = TimeZone(abbreviation: "UTC")
dateFormatterPrint.dateFormat = "HH:mm"
let resultTime = dateFormatterPrint.string(from: date1!)
print("time:\(String(describing: resultTime))")
For kotlin create Extension you can check it out
The first Step convert the String to local Date here dateFormat is Your input data formate and timeZone is input Time Zoon
fun String.toDate(dateFormat: String = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'", timeZone: TimeZone = TimeZone.getTimeZone("UST")): Date? {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)}
Secon Step is to convert local time into time formate you want like : 2022 23 12 10:50:05
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)}
Simple call these functions like this
fun String.convertToLocalTime():String{
val localFormat="dd-MM-yyyy HH:mm:ss"
this.toDate()?.formatTo(dateFormat = localFormat)?.let {
return it
}
return ""}

How to convert string to NSDate in Swift?

How can I convert a string like 05/18/2017 this to NSDate?
I am trying to convert this string to NSDate so that I can extract the day as 18 and month as 05 and year as 2017. How can I convert this or can extract those values from strings.
func toDate(dateString : String, dateFormat : String = "yyyy-MM-dd'T'HH:mm:ssX")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Now in code below selectedValue is 05/18/2017 but NSDateFromString always shows nil value:
let nsdateFromString = String.toDate(selectedValue)
What can I do in this case?
The default dateFormat value of your function toDate not matching the selectedValue's date format, so you need to pass dateFormat argument also with your method call with value MM/dd/yyyy.
let nsdateFromString = String.toDate(dateString: selectedValue, dateFormat: "MM/dd/yyyy")
**in SWIFT 3.0,**
let strDate = "12/21/2017"
let datefrmter = DateFormatter()
datefrmter.dateFormat = "mm/dd/yyyy"
let date = datefrmter.date(from: strDate)
print(date)
func convertSToD(date : String)-> Date?{
if date != "NA"{
let interval = Double(date)
let dateFormat = Date(timeIntervalSince1970: interval!)
return dateFormat
}
return nil
}
Try this :-
func toDate(dateString : String, dateFormat : String = "MM/dd/yyyy")-> NSDate!{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = dateFormat
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
let convertedDate = dateFormatter.dateFromString(dateString)
return convertedDate
}
Convert Current date and time
let formatter1 = DateFormatter()
let date1 = Date.init()
formatter1.dateFormat = "dd-MMM-yyyy hh:mm a"
let days = formatter1.string(from: date1 as Date)
print(days)
//in Swift 3.0 converting string to NSDate with its format
let dateString = self.scoring_date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
dateFormatter.locale = Locale.init(identifier: "en_GB")
self.dateObj = dateFormatter.date(from: dateString! as String )!
dateFormatter.dateFormat = "MM-dd-yyyy"
print("Dateobj: \(dateFormatter.string(from: self.dateObj))")
//converting NSDate to String
let today = Date()
today.toString(dateFormat: "dd-MM")

Converting String to Date using dd-MM-yyyy get nil in Xcode 8 in Swift 3.0

if I choose date like let dateString = "2014-01-12", How would I convert string to
dateFormatter.dateFormat = "yyyy-MM-dd"
and then in below format
dateFormatter.dateFormat = "dd-MM-yyyy"
I get nil values in Xcode 8 in Swift 3.0
{
let dateString = "2014-01-12"
dateFormatter.locale = Locale(identifier:"ja_JP")
dateFormatter.dateFormat = "dd-MM-yyyy"
print(dateFormatter.date(from:dateString))
}
or
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)! as Date
dateFormatter.dateFormat = "dd-MM-yyyy"
s = dateFormatter.date(from: dateString)! as Date
print("SecondDate\(s)")
In Xcode 7 it works fine.
If you want to convert to date formate yyyy-MM-dd to dd-MM-yyyy then your last line should be.
let dateString = "2014-01-12"
dateFormatter.dateFormat = "yyyy-MM-dd"
var s = dateFormatter.date(from: dateString)
dateFormatter.dateFormat = "dd-MM-yyyy"
Get formatted date like this
let dateStr = dateFormatter.string(from: s)
Instead of
s = dateFormatter.date(from: dateString)! as Date
You need to just change format of DateFormatter and get it as the String.
Need to change date string into "date string" as Date then you can change into your particular format. For every format you need to do this first.
You can use the code below.
Swift 3
extension String {
func changeDate(_ mydate:String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = DateFormatter.Style.long
dateFormatter.dateFormat = "yyyy-MM-dd"
let convertedDate = dateFormatter.date(from: mydate)
dateFormatter.dateFormat = "dd-MM-yyyy"
let date = dateFormatter.string(from: convertedDate!)
return date
}
}
You can use this
let dateString = "2014-01-12"
let dateFormatterNew = DateFormatter()
dateFormatterNew.dateFormat = "yyyy-MM-dd"
let date = dateFormatterNew.date(from: dateString)! as Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy"
let dateNew = dateFormatter.string(from: date )
print(dateNew)
do it like this
let datestring = "2014-01-12"
let dateF = NSDateFormatter()
dateF.dateFormat = "yyyy-MM-dd"
let firstDate = dateF.dateFromString(datestring)
dateF.dateFormat = "dd-MM-yyyy"
let newDateString = dateF.stringFromDate(firstDate!)
print("NEW DATE FORMAT IS : \(newDateString)")

Convert date string swift

I have a date string in this format:
2016-06-20T13:01:46.457+02:00
and I need to change it to something like this:
20/06/2016
Previously I have always used this library -> SwiftDate to manipulate the dates, but it doesn't work now.
I tried also something like:
let myDate = self.dateNoteDict[indexPath.row]!
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss.SSSSxxx"
let date = dateFormatter.dateFromString(myDate)
print("date -> \(date)")
but it doesn't work. How can I do?
Thanks in advance.
The standard ISO8601 date format with fractional seconds and time zone is
yyyy-MM-dd'T'HH:mm:ss.SSSZ
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.dateFromString(myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.stringFromDate(date)
Swift 3:
let myDate = "2016-06-20T13:01:46.457+02:00"
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX") // edited
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = dateFormatter.date(from:myDate)!
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
In macOS 10.13+, iOS 11+ ISO8601DateFormatter is an alternative as input formatter
let myDate = "2016-06-20T13:01:46.457+02:00"
let inputFormatter = ISO8601DateFormatter()
inputFormatter.formatOptions = [.withFullDate, .withFullTime, .withFractionalSeconds]
let date = dateFormatter.date(from:myDate)!
let outputFormatter = DateFormatter()
outputFormatter.locale = Locale(identifier: "en_US_POSIX")
outputFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
I always use this code while converting String to Date .
(Swift 3)
extension String
{
func toDate( dateFormat format : String) -> Date
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = format
if let date = dateFormatter.date(from: self)
{
return date
}
print("Invalid arguments ! Returning Current Date . ")
return Date()
}
}
and just call like . .
print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
//Capital HH for 24-Hour Time
I always use this code while converting String to Date. (Swift 4.2)
let myDate = datePicker.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)
You can try manually also:
let myDate = "2019-02-22T08:21:11+0000"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let date = myDate
dateFormatter.dateFormat = "dd/MM/yyyy"
let dateString = dateFormatter.string(from:date)
print(dateString)

Resources