2014-07-02 9 views
12

Mam datę "2014-07-02 20:57:38 +0000" i chcę sformatować ją jako "Dzisiaj o 20:57". Chcę tego, jeśli ciąg jest wczoraj, a następnie wyświetlić go jako "Wczoraj o 9:00 rano". Jeśli nie jest to dziś ani wczoraj, po prostu pokaż aktualną datę, np. "27/6 o 19:53".Jak wyświetlić datę z ludzkim językiem, np. "Dzisiaj o xx: xx pm", "Wczoraj o xx: xx am"?

Udało mi się uzyskać czas w formacie "8:57" z kodem poniżej.

  var formatter : NSDateFormatter = NSDateFormatter() 
      formatter.dateFormat = "h:mm a" 

      // message.createdAt is the date 
      let dateString = formatter.stringFromDate(message.createdAt) 
      println(dateString) 

      //output = 8:57 AM 

Jednak, gdy użyję następującego kodu, zwraca pusty ciąg.

  var formatter : NSDateFormatter = NSDateFormatter() 
      formatter.dateFormat = "h:mm a" 
      formatter.doesRelativeDateFormatting = true //<-- This doesn't work 

      let dateString = formatter.stringFromDate(message.createdAt) 
      println(dateString) 

      //output = (nothing, its a blank string) 

Jak wykonać tę pracę i wyświetlić "Dzisiaj" lub "Wczoraj" w Swift?

+0

** Swift 3 Odpowiedź: ** https://stackoverflow.com/a/46027060/3400991 –

Odpowiedz

16

Powód, dla którego jest pusty, oznacza, że ​​format daty zawiera tylko komponenty czasu. W połączeniu z .doesRelativeDateFormatting, który daje pusty ciąg znaków. Jeśli chcesz, aby niestandardowy format czasu, myślę, że trzeba oddzielne formatek do daty i czasu:

let now = NSDate() 

let dateFormatter = NSDateFormatter() 
dateFormatter.dateStyle = .MediumStyle 
dateFormatter.doesRelativeDateFormatting = true 

let timeFormatter = NSDateFormatter() 
timeFormatter.dateFormat = "h:mm a" 

let time = "\(dateFormatter.stringFromDate(now)), \(timeFormatter.stringFromDate(now))" 
println(time)  // prints "Today, 5:10 PM" 
+2

Właściwie wystarczy tylko jeden. Można zrobić to lubią: var formater: NSDateFormatter = NSDateFormatter() formatter.dateStyle = NSDateFormatterStyle.ShortStyle formatter.timeStyle = NSDateFormatterStyle.ShortStyle formatter.doesRelativeDateFormatting = true var DateString = formatter.stringFromDate (NSDate()) –

+0

To rozwiązanie nie zapewnia prawidłowego czasu dla większości stref czasowych oraz czasu letniego/zimowego. Zobacz poniżej rozwiązanie Incyc. – Vincent

4

spróbuj tego

let dateFormatter = NSDateFormatter() 
dateFormatter.dateStyle = .ShortStyle 
dateFormatter.timeStyle = .ShortStyle 
dateFormatter.doesRelativeDateFormatting = true 

let date = NSDate() 
let dateString = dateFormatter.stringFromDate(date) 
+0

Mówi "NSDateFormatter nie ma członka o nazwie localizedStringFromDate" –

+0

@HenryNgan Niestety nie zdawałem sobie sprawy, że była to metoda klasy, poprawiona teraz w edycji –

5

Z Swift 3, Apple Developer API Reference stwierdza o DateFormatter „s dateFormat nieruchomości:

należy ustawić tę właściwość tylko podczas pracy z wielkoformatowych przedstawień stałych, jak to omówiono w Working With Fixed Format Date Representations. W przypadku reprezentacji widocznych dla użytkownika należy używać właściwości dateStyle i timeStyle lub metody setLocalizedDateFormatFromTemplate(_:), jeśli żądanego formatu nie można uzyskać przy użyciu wstępnie zdefiniowanych stylów; obie te właściwości i ta metoda zapewniają zlokalizowaną reprezentację daty odpowiednią do wyświetlenia użytkownikowi.


DateFormatterdateStyle nieruchomość ma następującą deklarację:

formatu daty odbiornika.

var dateStyle: DateFormatter.Style { get set } 

W ten sam sposób, DateFormattertimeStyle nieruchomość ma następującą deklarację:

Styl czasowy odbiornika.

var timeStyle: DateFormatter.Style { get set } 

Zauważ, że DateFormatter.Style jest enum z następujących przypadków: none, short, medium, long, full.

Należy również pamiętać, że doesRelativeDateFormatting działa tylko po ustawieniu instancji dateStyle i/lub timeStyle dla ciebie DateFormatter.


Poniższy kod zabaw pokazać jak wyświetlanie dat w żądanym formacie wykorzystaniem DateFormatterdateStyle i timeStyle właściwości.

import Foundation 

let now = Date() // 2017-03-12 14:53:34 +0000 
let yesterday = Calendar.current.date(byAdding: .day, value: -1, to: now)! // 2017-03-11 14:53:34 +0000 
let aWeekAgo = Calendar.current.date(byAdding: .weekOfMonth, value: -1, to: now)! // 2017-03-05 14:53:34 +0000 

let dateFormatter = DateFormatter() 
dateFormatter.dateStyle = .long 
dateFormatter.timeStyle = .short 
dateFormatter.doesRelativeDateFormatting = true 

let nowString = dateFormatter.string(from: now) 
print(nowString) // prints: Today at 3:53 PM 

let yesterdayString = dateFormatter.string(from: yesterday) 
print(yesterdayString) // prints: Yesterday at 3:53 PM 

let aWeekAgoString = dateFormatter.string(from: aWeekAgo) 
print(aWeekAgoString) // prints: March 5, 2017 at 3:53 PM 
Powiązane problemy