Jags
Jags

Reputation: 143

How to Parse date in Simple date format in arabic locale?

i have date coming from server & is in the format = "2013-01-20T16:48:43" my application support Both Arabic & English Locale. But when i change the locale to Arabic the date is not parsing its giving me parse exception. till now what i have written is

private static Date parseJsonDate(final String string) throws Exception
    {
    final String change_Locale = Locale.getDefault().getISO3Language();
            if (change_Locale.equalsIgnoreCase("ara"))
            {

                System.out.println(":: Date :::" + string);
                final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", new Locale("ar"));

                System.out.println("new date " + format.parse(string));
                return format.parse(string);

Upvotes: 8

Views: 8341

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79085

Your error seems to be due to some bug in the older version of Java.

Note that in March 2014, the modern Date-Time API supplanted the legacy date-time API and since then it is strongly recommended to switch to java.time, the modern date-time API.

The java.time API has a specialised type, LocalDateTime to represent an object that has just date and time units, and no timezone information.

Demo:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

class Main {
    public static void main(String[] args) throws ParseException {
        DateTimeFormatter parser = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss", new Locale("ar"));
        LocalDateTime ldt = LocalDateTime.parse("2013-01-20T16:48:43", parser);
        System.out.println(ldt);

        // Alternatively, as suggested by Basil Bourque
        parser = DateTimeFormatter.ISO_LOCAL_DATE_TIME.withLocale(new Locale("ar"));
        System.out.println(LocalDateTime.parse("2013-01-20T16:48:43", parser));

        // Your parser
        final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", new Locale("ar"));
        System.out.println(format.parse("2013-01-20T16:48:43"));
    }
}

Output:

2013-01-20T16:48:43
2013-01-20T16:48:43
Sun Jan 20 16:48:43 GMT 2013

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Upvotes: 4

GrIsHu
GrIsHu

Reputation: 23638

Do not parse your date into the Arabic it will give you error alwayz besides try as below by setting the Locale ENGLISH only.

final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);

Upvotes: 13

Related Questions