Prajnaranjan Das
Prajnaranjan Das

Reputation: 1428

How to convert a date of any language to a specific language

How to convert a date of any language(Arabic) to a specific language(English).

While changing the region format to arabic, the dates are getting changed. When I am picking the date value from some controls(UIButtons or UILabels) for saving in database, its picking the date in arabic language and saving in the same format. Here I want to convert the date from arabic to english before saving it in database.

I tried this but its returning nil

NSDate *currentDate = //My date coming like  “٢٠١٤-٠٥-١٥ ١٢:١٠:٢٣ ”
NSDateFormatter *formatter=[[NSDateFormatter alloc] init];
NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[formatter setLocale: usLocale];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:s a"];
NSString *formattedDate = [formatter stringFromDate: currentDate];

Can anyone please help me ?

Upvotes: 1

Views: 2460

Answers (4)

Amr Angry
Amr Angry

Reputation: 3851

You may use this to get the date with preferred local

 NSDate * dateNow = [NSDate new];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];

[dateFormat setLocale: usLocale];

[dateFormat setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

NSString *   dateString = [dateFormat stringFromDate:dateNow];

Upvotes: 0

Prajnaranjan Das
Prajnaranjan Das

Reputation: 1428

I solved in this way

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:s"];
    NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setLocale:usLocale];
    NSString *dateString = [dateFormatter stringFromDate:myDate];

Upvotes: 10

Hao
Hao

Reputation: 134

You should use UIDatePicker as the input instead of UIButtons or UILabels. Save the timeIntervalSince1970 into your database, so that it can be presented by any language.

NSDate *currentDate = //My date coming like  “٢٠١٤-٠٥-١٥ ١٢:١٠:٢٣ ”
NSTimeInterval timeToBeSavedInDatabase = [currentDate timeIntervalSince1970];
//in the future, you can show this date in any language
NSString *dateString = [formatter stringFromDate:[NSDate dateWithTimeIntervalSince1970]];

Upvotes: 0

gnasher729
gnasher729

Reputation: 52632

You shouldn't store dates in any language. You should store NSDate, which has no language or locale or time zone, and display it as appropriate. If your database cannot store NSDate, you can store [myDate timeIntervalSince1970] and convert it to an NSDate using the class method dateWithTimeIntervalSince1970:

Upvotes: 4

Related Questions