How to convert a String of this type to a Date Object

Asked

Viewed 147 times

3

I’m working with an Ontology at Protegé 4.1 and I have a Dataproperty that is a Datetime.

I’m taking this Datetime this way:

["2015-06-30T16:38:53"^^xsd:dateTime]

How do I put the date like this on a Java Date object? (I’m using Java 7)

1 answer

3


If the string is even in the form it presented, also containing the type of XML data, ie, ["2015-06-30T16:38:53"^^xsd:dateTime], a way would be to recover only the relevant part with a regular expression, and then use a DateFormat.

An example of regular expression would be one like this:

\d+\-\d+\-\d+T\d+\:\d+\:\d+

A complete example would look like this:

final String dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
final String dateOnOWL = "[\"2015-06-30T16:38:53\"^^xsd:dateTime]";
final Pattern pattern = Pattern.compile("\\d+\\-\\d+\\-\\d+T\\d+\\:\\d+\\:\\d+");
final Matcher matcher = pattern.matcher(dateOnOWL);

if (matcher.find()) {
    final String result = matcher.group();
    final DateFormat sdf = new SimpleDateFormat(dateFormat);
    final Date date = sdf.parse(result);
    System.out.println(date);
} else {
    System.out.println(String.format("Padrão não encontrado em %s", dateOnOWL));
}

Regular expression is just an example of how to apply, you can improve it by using this approach.

The simple form is informing from which position the formatter (the DateFormat) should start using the pattern we are using. To do this you should use a ParsePosition informing that we will start from the index position 2, that is, of 2 of 2015. As the default will only go up to seconds, the formatter will disregard the rest.

An example would be something like this, which generates the same result:

final String dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
final String dateOnOWL = "[\"2015-06-30T16:38:53\"^^xsd:dateTime]";
final DateFormat sdf = new SimpleDateFormat(dateFormat);
final ParsePosition position = new ParsePosition(2);
final Date date = sdf.parse(dateOnOWL, position);
System.out.println(date);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.