Frage

First of all I want to say thanks in advance for helping me.

I want to know how can I create a date on a label using Xcode, and the date will follow the same date like in iphone.

Thanks

War es hilfreich?

Lösung

Here's one simple approach

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//uncomment to get the time only
//[formatter setDateFormat:@"hh:mm a"];
//[formatter setDateFormat:@"MMM dd, YYYY"];
[formatter setDateStyle:NSDateFormatterMediumStyle];


//get the date today
NSString *dateToday = [formatter stringFromDate:[NSDate date]];

UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320.0f, 20.0f)];
[label setText:dateToday];
[formatter release];

//then add to a view

Andere Tipps

Creating the text date is simple, but the real question is what is your data source that you want to make the date text out of?

The date can be formatted and set in label as below.

NSDate *today = [NSDate date];
NSDateFormatter *dformat = [[NSDateFormatter alloc] init];
[dformat setDateFormat:@"dd:MM:YYYY"];
myLabel.text = [dformat stringFromDate:today];

NSDateFormatter handle format of string dates.

Instances of NSDateFormatter create string representations of NSDate objects, and convert textual representations of dates and times into NSDate objects.

Try this and see:

// Set date format according to your string date format
// e.g.: For, 
// 22-12-1996 -> @"dd-MM-yyyy"
// 22/12/1996 -> @"dd/MM/yyyy"
// 1996-12-22 03:45:20 -> @"yyyy-MM-dd HH:mm:ss"

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"dd/MM/yyyy";
//dateFormatter.dateFormat = @"dd-MM-yyyy";

NSDate *date = [dateFormatter dateFromString:dateString];
if(date == nil) {
    correctFormat = false;
}
NSLog("Date: %@",date);

Note: Each pairs of characters in date format relates relevant date component with date instance. You can create any type of date format using date string pattern.

Here is document by Apple: Date Formatters

  • Date (Day): dd
  • Month: MM or MMM or MMMM
  • Year: yy or yyyy

Here is list of date formats: Date Formats

Here is solution in Swift

var today = Date()
var d_format = DateFormatter()
d_format.dateFormat = "dd:MM:yyyy"
label.text = dformat.string(from: today)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top