logo
Tags down

shadow

Sorting array of date from newest to oldest in Swift 4


By : user2176377
Date : October 14 2020, 02:21 PM
Does that help I am curious how to sort dates in form of Strings in an array. Most likely I would leave them in the same array and sort them the right way. Many attempts I have seen are with two. Also, they weren't the right time format so I want to know how to sort it with the "dd.MM.yyyy" format. Most likely with only the last two numbers of the year. Is that possible? , This is another answer with an updated POST structure.
code :
struct Post {
var title: String
var date: String
var user: String
}

extension Post{
static  let isoFormatter : ISO8601DateFormatter = {
    let formatter =  ISO8601DateFormatter()
        formatter.formatOptions = [.withFullDate,]
    return formatter
   }()

var dateFromString : Date  {
    let  iSO8601DateString = date.components(separatedBy: ".").reversed().joined(separator: ".")
    return  Post.isoFormatter.date(from: iSO8601DateString)!
}
}

var uploadTimes = [Post(title: "", date: "05.09.2018", user: ""),
               Post(title: "Hello", date: "02.10.2018", user: "Roman"),
               Post(title: "Hi", date: "01.10.2018", user: "Roman"),
               ]

//sort dates
let dates = uploadTimes.compactMap { $0.dateFromString }
print(dates)
let sortedDates = dates.sorted { $0 > $1 }
print(sortedDates)

//sort posts
let sortedPost = uploadTimes.sorted{ $0.dateFromString > $1.dateFromString  }
print(sortedPost)
extension Post{
static  let isoFormatter : ISO8601DateFormatter = {
    let formatter =  ISO8601DateFormatter()
        formatter.formatOptions = [.withInternetDateTime]
    return formatter
   }()

   var dateFromString : Date  {

  let components = date.components(separatedBy: " ")
  let  iSO8601DateString =
        (components.last!).components(separatedBy: ".").reversed().joined(separator: ".") + "T" + (components.first!) + ":00+00:00"
    return  Post.isoFormatter.date(from: iSO8601DateString)!
   }
}

 var uploadTimes = [Post(title: "", date: "01:20 05.09.2018", user: ""),
               Post(title: "Hello", date: "01:21 02.10.2018", user: "Roman"),
               Post(title: "Hi", date: "01:22 02.10.2018", user: "Roman"),
               ]


Share : facebook icon twitter icon

Sorting HTML/JavaScript timeline by date (sort by oldest/newest)


By : Tiago Diogo
Date : March 29 2020, 07:55 AM
help you fix your problem After switching all the id="date"'s to class="date"'s, you should do something like: ---> This Here JSFiddle <---
or see below...
code :
$(function(){
    var itemsArray = $('div.item');
    itemsArray.sort(function(a,b){
        var aTime = new Date($(a).find('.date').text()).getTime();
        var bTime = new Date($(b).find('.date').text()).getTime();
        return aTime - bTime;
    });

    $('#sortAsc').click(function(){
        $("#container").empty();
        $(itemsArray).each(function(){
            $("#container").prepend($(this));
        });
    });

    $('#sortDesc').click(function(){
        $("#container").empty();
        $(itemsArray).each(function(){
            $("#container").append($(this));
        });
    });
})

How can I sort arrays of time/date from oldest to newest in Swift?


By : David
Date : March 29 2020, 07:55 AM
it helps some times Array has a built-in method sort which allows you to provide a closure to sort the objects in it. Assuming your variable is called dates, you can sort the NSDates inside it like this:
code :
dates.sort { (a, b) -> Bool in
    a.earlierDate(b) == a
}

How to order table view cell from newest to oldest instead of from oldest to newest


By : Christina
Date : March 29 2020, 07:55 AM
will help you The problem as others have mentioned is not the table. You have to provide your data in order and since you're getting it from coredata it's fairly easy
code :
static func retrieveNotes() -> [Note] {
    let fetchRequest = NSFetchRequest<Note>(entityName: "Note")
    fetchRequest.sortDescriptors = [NSSortDescriptor(key:"date", ascending: true)] //date would be whatever theKeyWhereYouStoreTheDateInYourDatabaseIs
    do {
        let results = try managedContext.fetch(fetchRequest)
        return results
    } catch let error as NSError {
        print("Could not fetch \(error)")
    }
    return []
}

Need help sorting a collection of arrays based on oldest to newest date PHP/laravel


By : user1256783
Date : March 29 2020, 07:55 AM
around this issue PHP has a few neat functions that can help with this. First being array_multisort() which you can read about at http://php.net/manual/en/function.array-multisort.php
Using this function you can sort either multiple arrays at a time or, in your case, a multidimensional array.
code :
$ar = array(
       array(3, 5, 1, 2, 4),
       array(1, 2, 3, 4, 5),
       array(2, 4, 1, 5, 3),
       array(0, 7, 8, 9, 6),
       array("apples", "bananas", "organges", "pears", "pineapples")
      );
array_multisort($ar[0], SORT_ASC, SORT_NUMERIC,
                $ar[1], 
                $ar[2], 
                $ar[3], 
                $ar[4]);
echo "<br>";
var_dump($ar);
array(5) { 
  [0]=> array(5) { 
    [0]=> int(1) 
     [1]=> int(2) 
     [2]=> int(3) 
     [3]=> int(4) 
     [4]=> int(5) } 
  [1]=> array(5) { 
    [0]=> int(3) 
    [1]=> int(4) 
    [2]=> int(1) 
    [3]=> int(5) 
    [4]=> int(2) } 
  [2]=> array(5) { 
    [0]=> int(1) 
    [1]=> int(5)  [2]=> int(2) 
    [3]=> int(3) 
    [4]=> int(4) } 
  [3]=> array(5) { 
    [0]=> int(8) 
    [1]=> int(9) 
    [2]=> int(0) 
    [3]=> int(6) 
    [4]=> int(7) } 
  [4]=> array(5) { 
    [0]=> string(8) "organges" 
    [1]=> string(5) "pears" 
    [2]=> string(6) "apples" 
    [3]=> string(10) "pineapples" 
    [4]=> string(7) "bananas" 
  } 
} 
$dateAsSec = array()

foreach($date as $timestamp) {
  $dateAsSec[] = strtotime($timestamp);
}

$filteredArrays[] = $dateAsSec[]

$finalArray = array_multisort($filteredArrays[9], SORT_ASC, SORT_NUMERIC,
                              $filteredArrays[0],
                              $filteredArrays[1],
                              $filteredArrays[2],
                              $filteredArrays[3],
                              $filteredArrays[4],
                              $filteredArrays[5],
                              $filteredArrays[6],
                              $filteredArrays[7],
                              $filteredArrays[8]);

How to sort a 3 dimensional array by element containing date, from newest to oldest


By : user3241006
Date : March 29 2020, 07:55 AM
Does that help You can do this as a two-stage process. First, use array_walk with array_multisort to sort the inner arrays by datetime. Then use usort, comparing the maximum datetime values from the inner arrays:
code :
array_walk($arr, function (&$v) { array_multisort(array_column($v, 'datetime'), SORT_DESC, $v); });
usort($arr, function ($a, $b) {
    return strcmp(max(array_column($b, 'datetime')), max(array_column($a, 'datetime')));
});
print_r($arr);
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [personNum] => 4
                    [type] => status
                    [datetime] => 2019-05-26 16:04:24
                )
            [1] => Array
                (
                    [personNum] => 3
                    [type] => status
                    [datetime] => 2019-05-26 15:59:53
                )
        )
    [1] => Array
        (
            [0] => Array
                (
                    [personNum] => 3
                    [type] => status
                    [datetime] => 2019-05-26 15:59:53
                )
            [1] => Array
                (
                    [personNum] => 2
                    [type] => comment
                    [datetime] => 2019-05-15 11:29:45
                )
        )
)
Related Posts Related Posts :
  • Issue with unwrapping [String] when using image cache
  • Swift and Xcode: How to Build and Run a GitHub repository of iOS Application?
  • Handing a completion with CloudKit
  • Update Uitableview cells button title
  • How to handle multiple text fields effectively in UITextField's shouldChangeCharactersIn
  • NativeScript RadListView component template
  • UITableViewCell constraints breaking when adding a new cell
  • How to implement a listener or while(true) to stop a waveform plot from scrolling once recorder has finished recording i
  • problem with attributed text for keyboard titleBarButton when using IQKeyBoardManager
  • iOS: Extract detected numbers and links from UITextView?
  • Does iOS/UIKit have built in support for scheduling scroll like dinging
  • Drawing directions from google map api
  • Bottom corners arent round
  • Keep original node lighting after using a light for another node
  • How to calculate proper keyboard contentInset for UIScrollView inside of a modally presented form sheet UIViewController
  • update key values of NSManagedObjects safely
  • Why would Xcode show MUCH more memory use than Instruments for SceneKit app?
  • iOS Drawer UI that only works when breakpoint inserted
  • 'attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update' when inserting a row i
  • Problem when attempting to loop AVPlayer (userCapturedVideo) seamlessly
  • Accessing information within a NSDictionary
  • Importing and Using a Swift SnapshotTesting Framework with Carthage
  • How do I swap the first and second items in an array of strings?
  • How to soften begin and endUpdates in TableView
  • Proper way to create geometry base view in code
  • Passing data between two view controllers in a tab controller
  • PDF to Base64 on Ionic 3 app for Android and iOS platforms
  • PWA-Icon not used by iOS Devices
  • UICollectionView dynamic header size calculation
  • How best to remove all UIViewcontrollers and goto a single UIViewController?
  • How to generate Google Place API session token?
  • Thread 1: Fatal error: NSArray element failed to match the Swift Array Element type
  • How to get all custom tableview cell textField and textView value outside tableView
  • How do I fix, App Store Rejected app for external tester: Reason: Performance: App Completeness?
  • Validate Alamofire Response for both HTTP 200 and 500 status codes
  • How to check existing versions in Test Flight
  • Execute Completion Handler in DispatchGroup
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org