Converting UIDatePicker result to unix timestamp - ios

My issue is trying to convert a Date Picker result into a unix timestamp. My client is adamant that it'd be saved as a unix timestamp into Firebase database. Im also quite new to the swift so...
let myTimeStamp = NSDate(timeIntervalSince1970: self.datePicker?.date)
this is the result of datePicker: 2016-12-03 00:56:00 +0000
This is the error: Cannot convert value of type 'Date?' to expected argument type 'TimeInterval' (aka 'Double')
Please help sirs & ma'ams!

You already have the Date. Since you want the timestamp, call:
let myTimeStamp = self.datePicker?.date.timeIntervalSince1970
myTimeStamp will be an NSTimeInterval with a value in Unix time.

Including swift 5+
**Pass date like yourDatePicker.date **
func getTimeStampFromDate(date: Date) -> String {
return String(format: "%.0f", (date.timeIntervalSince1970 * 1000))
}

Related

Sort received dates from response in swift

I am working on code where I am receiving lots of data associated with dates
each object having one date parameter and there might many objects with the same date.
I need to show this all objects in UITableView. each object as one cell.
I succeed in that,
I need to get unique dates from the response array of objects.
Those unique dates will be stored in an array which will act as a number of sections of my table view with section header title will be the date from the unique date array.
somehow I am able to sort out that with what I want,
The only problem I am facing is I am not able to sort the unique date array
every time the sequence change.
I need the latest date as the first date and the oldest date as the end date.
How to achieve this in swift.
Following is a piece of code I have written
let sortedKeys = Array(dictValue.keys).sorted(by: {$0 > $1})
print(sortedKeys)
here dicValue.keys is my unique date array and I wanted to sort it.
Following is a sample response I am getting
["08/03/2021”, “10/02/2021”, "26/04/2021", "25/03/2021”, "09/12/2020”, , "27/04/2021”, "23/03/2021”, "11/01/2021”, "05/03/2021”, "09/03/2021”, "16/10/2020", "19/03/2021", "12/10/2020" ]
and after applying sort I am getting the following output
[“27/04/2021", "26/04/2021", "25/03/2021", "23/03/2021", "19/03/2021", "16/10/2020", "12/10/2020", "11/01/2021", "10/02/2021", "09/12/2020", "09/03/2021", "08/03/2021", "05/03/2021”]
where dates are not properly sorted out.
Can anyone please help me out with it.
Thanks in advance.
This string date format is inappropriate for sorting, because the most significant component is day. Only a date format like yyyy/MM/dd can be sorted properly by comparison operator >.
However this is Swift. The closure can contain anything as long as it returns a Bool. You could sort the array with a custom sort algorithm. It splits the strings into components and sorts first year then month then day
let sortedKeys = dictValue.keys.sorted { (date1, date2) -> Bool in
let comps1 = date1.components(separatedBy: "/")
let comps2 = date2.components(separatedBy: "/")
return (comps1[2], comps1[1], comps1[0]) > (comps2[2], comps2[1], comps2[0])
}
print(sortedKeys)
If you want to sort a date, just sort a Date. Date supports Hashable and can be used as a dictionary key, you could map your original dictionary and by using a DateFormatter to format your string keys into Dates then you can easily sort them.
let dictionary = ["08/03/2021": 2, "10/02/2021": 5, "26/04/2021" : 6]
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy" // You should probably adjust other properties of the formatter
let newDict = Dictionary(uniqueKeysWithValues:
dictionary.map { (key, value) -> (Date, Int) in
print("Key: \(key)")
return (formatter.date(from: key)!, value)
})
let sortedDates = newDict.keys.sorted { $0 > $1 }
let value = newDict[sortedDates[0]]

How to fix 'Cannot assign value of type 'NSDate' to type 'Date?'

I am a beginner with swift and I'm trying to complete my first app.
While I was typing the code, it showed me this:
Cannot assign value of type 'NSDate' to type 'Date?
at
newBirthday.birthdate = birthdate as NSDate
I tried writing statements for making that line of code work but it wouldn't. Every time now I am running it, I would get 6 errors.
let newBirthday = Birthday(context: context)
newBirthday.firstName = firstName
newBirthday.lastName = lastName
newBirthday.birthdayGift = birthdayGift
newBirthday.birthdate = birthdate as NSDate
newBirthday.birthdayID = UUID().uuidString
Starting with Swift 3, it no longer used Objective-c libraries NS
So if use Swift 3.0 or greater, then remove NS Prefix
In your case Birthday Object variable 'birthdate' is Date type not NSDate
if you can not assign NSDate in the Date object, for assign NSDate in Date you have cast first in Date.
newBirthday.birthdate = birthdate

unable to convert string date in Format yyyyMMddHHmmss to DateTime dart

i have a string containing date in format yyyyMMddHHmmss (e.g.) (20180626170555) and i am using following code to convert it into date time
dateTimeFromString(json['dateTime'], "yyyyMMddHHmmss")
exception is:
FormatException: Trying to read MM from 20180623130424 at position 14
what can be the reason?
DateTime.parse("string date here") accept some formatted string only. Check below examples of accepted strings.
"2012-02-27 13:27:00"
"2012-02-27 13:27:00.123456789z"
"2012-02-27 13:27:00,123456789z"
"20120227 13:27:00"
"20120227T132700"
"20120227"
"+20120227"
"2012-02-27T14Z"
"2012-02-27T14+00:00"
"-123450101 00:00:00 Z": in the year -12345.
"2002-02-27T14:00:00-0500": Same as "2002-02-27T19:00:00Z"
=> String to DateTime
DateTime tempDate = new DateFormat("yyyy-MM-dd hh:mm:ss").parse(savedDateString);
=> DateTime to String
String date = DateFormat("yyyy-MM-dd hh:mm:ss").format(DateTime.now());
Reference links:
Use intl for DateFormat from flutter package (https://pub.dev/packages/intl)
DateTime.parse() => https://api.dart.dev/stable/2.7.2/dart-core/DateTime/parse.html
intl DateFormat can't cope with your input string as it doesn't have any separators. The whole string gets consumed as the year. However DateTime.parse does cope with this (nearly). It happens to expect precisely the format you have (again, nearly).
One of the acceptable styles to parse is 20120227T132700, which just differs by the T date/time separator.
Try this:
String date = '20180626170555';
String dateWithT = date.substring(0, 8) + 'T' + date.substring(8);
DateTime dateTime = DateTime.parse(dateWithT);
to convert from "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" to 'MM/dd/yyyy hh:mm a'
date = '2021-01-26T03:17:00.000000Z';
DateTime parseDate =
new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse(date);
var inputDate = DateTime.parse(parseDate.toString());
var outputFormat = DateFormat('MM/dd/yyyy hh:mm a');
var outputDate = outputFormat.format(inputDate);
print(outputDate)
output
01/26/2021 03:17 AM
You can use DateFormat to parse a DateTime from string to an object
// With en_US locale by default
var newDateTimeObj = new DateFormat().add_yMd().add_Hms().parse("7/10/1996 10:07:23")
// with a defined format
var newDateTimeObj2 = new DateFormat("dd/MM/yyyy HH:mm:ss").parse("10/02/2000 15:13:09")
Check the doc here.
The Easient way convert a string into Date format is
print(DateTime.parse('2020-01-02')); // 2020-01-02 00:00:00.000
print(DateTime.parse('20200102')); // 2020-01-02 00:00:00.000
print(DateTime.parse('-12345-03-04')); // -12345-03-04 00:00:00.000
print(DateTime.parse('2020-01-02 07')); // 2020-01-02 07:00:00.000
print(DateTime.parse('2020-01-02T07')); // 2020-01-02 07:00:00.000
print(DateTime.parse('2020-01-02T07:12')); // 2020-01-02 07:12:00.000
print(DateTime.parse('2020-01-02T07:12:50')); // 2020-01-02 07:12:50.000
print(DateTime.parse('2020-01-02T07:12:50Z')); // 2020-01-02 07:12:50.000Z
print(DateTime.parse('2020-01-02T07:12:50+07')); // 2020-01-02 00:12:50.000Z
print(DateTime.parse('2020-01-02T07:12:50+0700')); // 2020-01-02 00:12:50.00
print(DateTime.parse('2020-01-02T07:12:50+07:00')); // 2020-01-02 00:12:50.00
From the docs, you need Single M to month in year :
dateTimeFromString(json['dateTime'], "yMdHms")
Basic information about how to convert String to Date and Date to string in flutter. Look at below link
https://quickstartflutterdart.blogspot.com/2018/10/how-to-convert-string-to-date-and-date.html
Might be it will be helped for others.
i did something like this (using the intl package)
final date = '7/10/1996';
final month = DateFormat.LLLL().format(DateTime.parse(date));
LLLL in the code above is date format skeleton meaning 'stand alone month', other date formatter is presented here
add String date as a parameter
DateTime.prase(String userString);
If you have a date and time string in a specific format, you can convert it to a DateTime object by using the parse() method. For example, if you have a string that contains “12/03/2019 9:45 AM”, you can use the parse() method to convert it to a DateTime object like this:
var dateTimeString = “12/03/2019 9:45 AM”;
var dateTimeObject = DateTime.parse(dateTimeString);
print(dateTimeObject); // 12/03/2019 09:45:00.000
The parse() method is very versatile and can handle a variety of different formats. If your string doesn’t follow a strict format, you can use tryParse() instead. This method will return null if it fails to parse the string.
for detail click here
https://mycodingwork.com/flutter-convert-string-to-datetime/
String startdate1="10/31/2022";
String endate1="11/02/2022";
DateTime start = new DateFormat("MM/dd/yyyy").parse(startdate1);
DateTime end = new DateFormat("MM/dd/yyyy").parse(enddate1);
DateTime s = DateTime(start.year, start.month, start.day);
DateTime to = DateTime(end.year, end.month, end.day);
int day= (to.difference(s).inHours / 24).round()+1;

Trying to convert NSDate to Date and getting warning

I am getting the following warning
Forced cast from 'NSDate?' to 'Date' only unwraps and bridges; did you
mean to use '!' with 'as'?
on the following line of code:
pickDate.date = item?.date as! Date
where pickDate is a UIDatePicker. The code works and if I try to follow the recommended fixes, they loop with other warnings or errors that are no better.
Any suggestions?
Using Swift 3.x (Xcode 8.3.3) I was able to get rid of the warning with:
pickDate.date = item.date! as Date
But this assumes "item" is not an optional anymore (on my code I can if-let it).
if let model = item, item?.date != nil{
pickDate.date = model.date
}
item is an Entity does not provide enough info (better include the definition of the entity), but according to the message, item?.data is of type NSDate? (aka Optional<NSData>). You can convert NSDate to Date with as-casting, as well as NSDate? to Date?:
(You usually do not use as! or as? when converting between NSDate and Date.)
if let theDate = item?.date as Date? {
pickDate.date = theDate
} else {
//Generally, silently ignoring unexpected value would be a bad habit.
print("`item?.date` is nil")
}
item maybe nil. then item?.data maybe nil.
try this:
pickDate.date = item!.date as! Date
or
pickDate.date = (item?.date)! as Date

getting specific object in fetchedObjects without iteration

My app has a custom object SSSchedule that I persist in CoreData, with a sortDescriptor of "date" (SSSchedule has a variable var date : NSDate?). Is there a more efficient method to finding a specific SSSchedule object with a specific date rather than iterating through the fetchedObjects array checking each for schedule.date == myDate as! NSDate?
My app references the fetchedObjects quite often, so I would imagine constantly mapping fetchedObjects to a dictionary of type [String : SSSchedule] (for example) every time the context is saved would affect performance...
Write a fetch request to return the objects matching that specific date from the datastore. If you are being consistent, then from what you've written you'll get back an array with one element.
Let Core Data do that searching for you. That's what it's for.
I think if you use a plist which has a Dictionary of Dictionaries. it could be a more what you need.
The first Dictionary will have a key of a tuple of (Day,Month,Year) which can be easily extracted from NSDate. and a value of a Dictionary which key is a tuple of (Hours, Minutes) also extracted from NSDate and a value of String which is the task to do at that time.
this way if you have a specific date, that date is the key to access only the tasks and events you have during that specific date in O(1) time complexity.
Now if you want to know if you have something at a specific time you access it in a similar way. The method is supposed to return String?. If there's a task at a specific time, it will return the task, otherwise it will return nil which means you're free at this time.
This is how the data structure should look [(Day, Month,Year):[(Hours,Minutes):String]]
Regarding extracting components from NSDate
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour |.CalendarUnitMinute
|.CalendarUnitYear|.CalendarUnitMonth|.CalendarUnitDay, fromDate: date)
let day = components.day
let month = components.month
let year = compononets.year
let hour = components.hour
let minutes = components.minutes
Use filter() to build a new array with any objects that match your criteria:
let newArray = fetchedObjects.filter() { $0.date == myDate as! NSDate }
Then check the count of newArray and handle accordingly - unless you know the dates are unique, there could be zero, one or more elements in the array.

Resources