البرمجة

تحويل تنسيق التاريخ في Objective-C

To convert the string “11/08/91” (MM/dd/yy) into “11/08/1991” (MM/dd/yyyy), you need to adjust the date format in your code. The issue in your code is that the date format for parsing (@"MM/dd/yyyy") does not match the actual format of the input string (@"MM/dd/yy"). Here’s the corrected code:

objective
NSString *strdate = @"11/08/91"; NSDateFormatter *dateformate=[[NSDateFormatter alloc]init]; [dateformate setDateFormat:@"MM/dd/yy"]; NSDate *date = [dateformate dateFromString:strdate]; [dateformate setDateFormat:@"MM/dd/yyyy"]; NSString *strConvertedDate = [dateformate stringFromDate:date]; NSLog(@"Converted Date is :%@",strConvertedDate);

This code first parses the input string into an NSDate object using the format @"MM/dd/yy", and then formats it back to a string using the format @"MM/dd/yyyy" to get the desired output. The strConvertedDate will contain the correctly formatted date string “11/08/1991”.

المزيد من المعلومات

عند استخدام NSDateFormatter في Objective-C لتحويل تنسيق التاريخ من “MM/dd/yy” إلى “MM/dd/yyyy”، يجب ملاحظة بعض النقاط الهامة:

  1. تنسيق الوقت الأصلي: في الكود الأصلي، كان تنسيق الوقت الذي تم تحويله “MM/dd/yy”. لذلك، عند استخدام setDateFormat:@"MM/dd/yyyy"، يجب أولاً تحديد تنسيق الوقت الأصلي بالطريقة الصحيحة.

  2. تحديد تنسيق الإخراج: بعد تحويل التاريخ، يجب استخدام NSDateFormatter مرة أخرى لتحديد تنسيق الإخراج المطلوب. في هذه الحالة، النص الناتج يجب أن يكون بتنسيق “MM/dd/yyyy”.

  3. تحويل النص الناتج إلى NSString: بعد الحصول على تاريخ محدد الصيغة، يمكن استخدام stringFromDate لتحويله إلى NSString ليتم طباعته أو استخدامه بالطريقة التي تريدها.

إليك الكود الذي يوضح هذه النقاط:

objective
NSString *strdate = @"11/08/91"; // تحديد تنسيق الوقت الأصلي NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init]; [inputDateFormatter setDateFormat:@"MM/dd/yy"]; NSDate *date = [inputDateFormatter dateFromString:strdate]; // تحديد تنسيق الإخراج NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init]; [outputDateFormatter setDateFormat:@"MM/dd/yyyy"]; NSString *strConvertedDate = [outputDateFormatter stringFromDate:date]; NSLog(@"Converted Date is :%@", strConvertedDate);

باستخدام هذا الكود، يجب أن تحصل على النتيجة المرجوة “11/08/1991” كمخرج صحيح.

زر الذهاب إلى الأعلى