extension Date { has no effect - ios

This is my original timestamp code
How should I modify to cite him
How should I modify the code to refer to the "extension Date {" code
func getDatas(){
if let timestamp = document.get("timestamp") as? TimeInterval {
let date = Date(timeIntervalSince1970: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, date: date)
...
...
...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! FeedCell
let post = self.postArray[indexPath.row]
let date = post.date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd HH:mm"
let dateString = dateFormatter.string(from: date)
self.getUserInfo(userEmail: postArray[indexPath.row].email,cell: cell)
cell.captionLabel.text = postArray[indexPath.row].caption
cell.postImage.sd_setImage(with: URL(string: postArray[indexPath.row].imageUrl))
cell.timeLabel.text = dateString
I want to change to the following date display method, but the changes have no effect
extension Date {
static func timeString(timeInterval: TimeInterval) -> String{
let date = getNowDateFromatAnDate(Date(timeIntervalSince1970: timeInterval/1000))
let formatter = DateFormatter()
if date.isToday() {
//是今天
formatter.dateFormat = "今天HH:mm"
return formatter.string(from: date)
}else if date.isYesterday(){
//是昨天
formatter.dateFormat = "昨天HH:mm"
return formatter.string(from: date)
}else if date.isSameWeek(){
//是同一周
let week = date.weekdayStringFromDate()
formatter.dateFormat = "\(week)HH:mm"
return formatter.string(from: date)
}else{
formatter.dateFormat = "yyyy-MM-dd HH:mm"
return formatter.string(from: date)
}
}
...
...
...
...
How should I modify to cite him

The static keyword allow us to attach the method to a class/struct rather than to instances of it.
And since the static func timeString(timeInterval: TimeInterval) -> String in your Date extension returns a string you can replace your Post date: Date variable with timeString: String and then you can access it directly:
if let timestamp = document.get("timestamp") as? TimeInterval {
let timeString = Date.timeString(timeInterval: timestamp)
let post = Post(email: email, caption: caption, imageUrl: imageURL, timeString: timeString)
// ...
}
cell.timeLabel.text = post.timeString

Related

how to remake the beginning of the week, not from Sunday, but from Monday

I use the library to display the calendar, I would like to make the week start on Monday and the calendar is displayed from the current date by 2017
https://github.com/miraan/CalendarDateRangePickerViewController
Image
changed the locale on russian language, but did not help
func getMonthLabel(date: Date) -> String {
var dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ru_RU")
dateFormatter.dateFormat = "MMMM yyyy"
return dateFormatter.string(from: date)
}
func getWeekdayLabel(weekday: Int) -> String {
var components = DateComponents()
components.calendar = Calendar.current
components.weekday = weekday
let date = Calendar.current.nextDate(after: Date(), matching: components, matchingPolicy: Calendar.MatchingPolicy.strict)
if date == nil {
return "E"
}
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "ru_RU")
dateFormatter.dateFormat = "EEEEE"
return dateFormatter.string(from: date!)
}
The problem was in this part of the code, corrected by 2 and managed to get the desired result.
override public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellReuseIdentifier, for: indexPath) as! CalendarDateRangePickerCell
cell.reset()
let blankItems = getWeekday(date: getFirstDateForSection(section: indexPath.section)) - 1
if indexPath.item < 7 {
cell.label.text = getWeekdayLabel(weekday: indexPath.item **+ 2** )
} else if indexPath.item < 7 + blankItems {
cell.label.text = ""

How to format date correctly

How do I format this date so that it is readable. I want it to show for example: "January 7th, 2018 7:30am". I tried to look at other answers but wasn't sure where to add the extension.
let date = Date(timeIntervalSince1970: request.timestamp / 1000)
dateCell.textLabel?.text = date.description
class Request {
var key:String
var sender:String
var recipient:String
var name:String
var location:String
var when:String
var whereStr:String
var message:String
var timestamp:Double
var status:String
init(dict: [String: Any]) {
self.key = dict["key"] as? String ?? ""
self.sender = dict["sender"] as? String ?? ""
self.recipient = dict["recipient"] as? String ?? ""
self.name = dict["name"] as? String ?? ""
self.location = dict["location"] as? String ?? ""
self.when = dict["when"] as? String ?? ""
self.whereStr = dict["where"] as? String ?? ""
self.message = dict["message"] as? String ?? ""
self.timestamp = dict["timestamp"] as? Double ?? 0.0
self.status = dict["status"] as? String ?? ""
}
Try This
func getCurrentDateTimeFromTimeStamp(timeStapm:String)->String{
let date = NSDate(timeIntervalSince1970:Double(timeStapm)!/1000)
let formatter = DateFormatter()
formatter.dateFormat = "MMMM d, yyyy HH:mm a"
return formatter.string(from: date as Date)
}
pass timestamp and get as date in string format as per your requirement just pass dateFormat.
use like this
dateCell.textLabel?.text = self.getCurrentDateTimeFromTimeStamp(timeStapm:"pass your timestamp")
You should use DateFormatter:
let formatter = DateFormatter()
formatter.format = "MMMM d, yyyy HH:mm a"
let dateString = formatter.string(from: date)
Use a dateFormatter object to style the date however you want
let format = DateFormatter()
format.format = "MM/dd/yyyy"
//get your date in string like this
let dateInString = format.string(from: date)
// this will give you "10/02/2018"
You can visit date format examples to see different format and how to get them.
You can add extension anywhere in the app and one (same name) extension for comlpete app. look below
import UIKit
class ViewControllerHellBoy: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
dateCell.textLabel?.text = self.userFriendlyFullDate()
}
}
extension Date: Dateable {
var formatter: DateFormatter { return DateFormatter() }
/** Return a user friendly hour */
func userFriendlyFullDate() -> String {
// Customize a date formatter
formatter.dateFormat = ""MMMM d, yyyy HH:mm a"" //Use format you want to
formatter.timeZone = TimeZone(abbreviation: "UTC") . // Time zone you wishes to provide
return formatter.string(from: self)
}
That is how you can use extensions. You can also create separate class and keep all extensions there.

FSCalender Events Show in swift

I am new to swift, Am using Fscalender in swift it's working fine, But I want add the Events to Fscalender, I can get events from Json
I Want Display the events in calender, I can try some of the code but its not working getting some errors pls help how to display events in calender
var EventsData = [Event]()
all events are stored Into Event
fileprivate lazy var dateFormatter2: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
return formatter
}()
inside Json
if let event_list = jsonData["events"] as? NSArray {
for i in 0 ..< event_list.count {
if let event = event_list[i] as? NSDictionary {
let data = event["date"]as?String
let newString = data?.replacingOccurrences(of: "/", with: "-")
print("new string data ",newString as Any)
self.compareDate(date: newString!)
self.EventsData.append(Event(
eventId: event["eventId"] as? String,
eventName:event["details"] as? String,
//eventDate: event["date"] as? String
eventDate: newString ))
}
}
}
Display the Events
func compareDate(date : String){
let date = date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFromString : NSDate = dateFormatter.date(from: date)! as NSDate
===>> After this line showing Fatal error
dateFormatter.dateFormat = "yyyy-MM-dd"
let datenew = dateFormatter.string(from: dateFromString as Date)
print("datee",datenew)
}
func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
let dateFormatter3 = DateFormatter()
dateFormatter3.dateFormat = "yyyy-MM"
let dateString3 = dateFormatter3.string(from: date)
//print("datenew1",dateString3)
strcond = dateString3 as NSString
print("datenew1",strcond!)
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dateString = self.dateFormatter2.string(from: date)
for d in EventsData{
let date = d.eventDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFromString : NSDate = dateFormatter.date(from: date!)! as NSDate
dateFormatter.dateFormat = "yyyy-MM-dd"
let datenew = dateFormatter.string(from: dateFromString as Date)
if datenew.contains(dateString) {
return 1
}
}
return 0
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventColorFor date: Date) -> UIColor? {
let dateString = self.dateFormatter2.string(from: date)
for d in EventsData{
let date = d.eventDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let dateFromString : NSDate = dateFormatter.date(from: date!)! as NSDate
dateFormatter.dateFormat = "yyyy-MM-dd"
let datenew = dateFormatter.string(from: dateFromString as Date)
print("new calendar",dateString)
if datenew.contains(dateString) {
return UIColor.purple
}
}
return nil
}
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
if monthPosition == .previous || monthPosition == .next {
calendar.setCurrentPage(date, animated: true)
print("title date",date)
}
}
how to show events in calendar ?
After some changes in my code it's working fine showing events in FsCalender
inside Json
if let event_list = jsonData["events"] as? NSArray {
for i in 0 ..< event_list.count {
if let event = event_list[i] as? NSDictionary {
self.EventsData.append(Event(
eventId: event["eventId"] as? String,
eventName:event["details"] as? String,
eventDate: event["date"] as? String
)
)
}
}
self.do_refresh()
}
func do_refresh()
{
DispatchQueue.main.async(execute: {
self.calender.reloadData()
return
})
}
Fscalender Implementation
func calendar(_ calendar: FSCalendar, willDisplay cell: FSCalendarCell, for date: Date, at position: FSCalendarMonthPosition) {
let dateFormatter3 = DateFormatter()
dateFormatter3.dateFormat = "yyyy-MM-dd"
let dateString3 = dateFormatter3.string(from: date)
strcond = dateString3 as NSString
}
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
let dateString = self.dateFormatter2.string(from: date)
print("this count first ",self.EventsData.count)
for d in EventsData{
let date = d.eventDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateFromString : NSDate = dateFormatter.date(from: date!)! as NSDate
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let datenew = dateFormatter.string(from: dateFromString as Date)
if datenew.contains(dateString) {
return 3
}
}
return 0
}
func calendar(_ calendar: FSCalendar, appearance: FSCalendarAppearance, eventColorFor date: Date) -> UIColor? {
let dateString = self.dateFormatter2.string(from: date)
for d in EventsData{
let date = d.eventDate
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
let dateFromString : NSDate = dateFormatter.date(from: date!)! as NSDate
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
let datenew = dateFormatter.string(from: dateFromString as Date)
if datenew.contains(dateString) {
return UIColor.init(red: 10, green: 200, blue: 399, alpha: 300)
}
}
return nil
}

Print func didn't print all itmes

I have a swift file Data.swift
extension NSDate {
convenience init(dateString: String) {
let dateStringFormatter = NSDateFormatter()
dateStringFormatter.dateFormat = "MM/dd/yyyy"
dateStringFormatter.timeZone = NSTimeZone(name: "GMT")
let date = dateStringFormatter.dateFromString(dateString)
self.init(timeInterval:0, sinceDate:date!)
}
func getDatePart() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "MM/dd/yyyy"
formatter.timeZone = NSTimeZone(name: "GMT")
return formatter.stringFromDate(self)
}
}
class GDate {
let image : String
let name : String
let date: String
init(gImage : String, gName : String, gDate: String) {
self.name = gName
self.image = gImage
self.date = NSDate(dateString: gDate).getDatePart()
}
}
struct Data {
let places = [
GDate(gImage: "image.png", gName: "USA", gDate: "04/26/2016"),
GDate(gImage: "image2.png", gName: "FAR", gDate: "03/26/2016"),
GDate(gImage: "image3.png", gName: "UK", gDate: "02/26/2016"),
GDate(gImage: "image4.png", gName: "GER", gDate: "01/26/2016")
]
}
in the tableView in the "cellForRowAtIndexPath" method
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! GamesViewCell
let gD = Data()
let entry = gD.places[indexPath.row]
let gDate = entry.date
let image = UIImage(named: entry.image)
cell.gameImageView.image = image
cell.gameNameLabel.text = entry.name
print(gDate)
return cell
in the debuger it only print the first and second date and ignore the rest ?!
"same for the names if I used it instead of the dates"
the debuger

NSDate to display only Date in TableViewCell

I am able to get NSDate to appear as date only and to show it in textfields to add and edit to core data but in the tableviewcell when using the subtitle style it comes out with both the date and time which I don't need thee time.
Any help is appreciated.
the following code is my NSDateFormatter
import Foundation
extension NSDate{
var stringValue: String{
return self.toString()
}
func toString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM-YYYY"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var dateValue: NSDate?{
return self.toDate()
}
func toDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "dd-MMM-YYYY"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
the following code is the subtitle style. date is called from cordite
cell.detailTextLabel!.text = "(ddate)"
OK, Found out what I was doing wrong. I added the following line above the cell.detail.textLabel and it works
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyy"
let dateForText = ddate as? NSDate
cell.detailTextLabel!.text = dateFormatter.stringFromDate(dateForText!)

Resources