-2

i know that maybe this is a replicated question, but i want to parse a string to convert it into Date object.I'm able to do this by doing:

SimpleDateFormat parser = new SimpleDateFormat("yyyy-M-d (HH:mm:ss.S)"); Date date = parser.parse(propertiesvalue[i]);

And it returns "date" in this format: Fri Jan 30 13:55:00 CET 2015 But i want to return something like:2015-01-30 (13:55:00.00) Data Object (NOT as String Object). I need it to insert Date in local Google Datastore.

ValeMarz
  • 5
  • 6

1 Answers1

0

String != datetime

Do not conflate a date-time object with a string that may represent its value.

A date-time object has no format. A date-time format represents a moment. A date-time object can generate a string. A date-time object can be created by parsing a string. But the date-time object and the string are always separate and distinct.

Avoid legacy classes

You are using troublesome old date-time classes that are now legacy, supplanted by the java.time classes.

Using java.time

Instant instant = Instant.now();               // Current moment in UTC
ZoneId z = ZoneId.of( "Pacific/Auckland" );  
ZonedDateTime zdt = instant.atZone( z );       // Same moment viewed as wall-clock time of particular region.

Generate a string to represent that object’s value in a certain format.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-M-d (HH:mm:ss.S)" , Locale.US );
String output = zdt.format( f );

Dump to console.

System.out.println( "instant.toString(): " + instant );  // Standard ISO 8601 format.
System.out.println( "zdt.toString(): " + zdt );          // Standard ISO 8601 format.
System.out.println( "output: " + output );               // Custom format.

See this code run live at IdeOne.com.

instant.toString(): 2017-04-15T06:00:58.521Z

zdt.toString(): 2017-04-15T18:00:58.521+12:00[Pacific/Auckland]

output: 2017-4-15 (18:00:58.5)


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154