1

I have a string in this format String oldstring = "Mar 19 2018 - 14:39";

How to convert this string to java object so that I get time and mins from date object.

I have tried like this,

import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class DateEg {
    public static final void main(String[] args) {
        SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");
    String oldstring = "Mar 19 2018 - 14:39";
        String time = localDateFormat.format(oldstring);
        System.out.println(time);
    }
}

But getting error, saying Cannot format given Object as a Date

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format given Object as a Date
    at java.base/java.text.DateFormat.format(DateFormat.java:332)
    at java.base/java.text.Format.format(Format.java:158)
    at DateEg.main(DateEg.java:9)

Is it possible to parse this string format in java?

Arun
  • 782
  • 2
  • 13
  • 25
  • 1
    Your format mask is off. The mask you specified has only hours and minutes but your timestamp has much more than this. – Tim Biegeleisen Apr 02 '18 at 11:18
  • 1
    You question title says "convert string to date". Are you sure you want to `format` and not to `parse`? – lexicore Apr 02 '18 at 11:19
  • 1
    We *format* object to text, we *parse* text to object. – Pshemo Apr 02 '18 at 11:22
  • I had misunderstanding between format and parse. thanks @Pshemo – Arun Apr 02 '18 at 11:27
  • @lexicore No. I want to parse the string. – Arun Apr 02 '18 at 11:28
  • @Arun Then call `parse`. – lexicore Apr 02 '18 at 11:29
  • FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 02 '18 at 19:43

4 Answers4

2

Try using this, this should work:

DateTimeFormatter formatter = DateTimeFormat.forPattern("MMM dd yyyy - HH:mm");
LocalDateTime dt = formatter.parse(oldstring);`

DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("HH:mm");
String time = timeFormat.format(dt).toString();`
Akshay Batra
  • 137
  • 7
2

User proper formatter with your code to parse string mentioned below

    SimpleDateFormat localDateFormat = new SimpleDateFormat("MMM dd yyyy - HH:mm");
    String oldstring = "Mar 19 2018 - 14:39";
    Date date=localDateFormat.parse(oldstring);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int hours = calendar.get(Calendar.HOUR_OF_DAY);
    int minutes = calendar.get(Calendar.MINUTE);
    int seconds = calendar.get(Calendar.SECOND);
Dhiraj
  • 870
  • 2
  • 12
  • 25
  • How to get only hour and mins from date object? – Arun Apr 02 '18 at 11:43
  • @Arun see my edited answer – Dhiraj Apr 02 '18 at 11:47
  • 1
    FYI, the troublesome old date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/9/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/9/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/9/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Apr 02 '18 at 19:43
2

tl;dr

LocalDateTime.parse(                   // Parse as a `LocalDateTime` because the input lacks indication of zone/offset.
    "Mar 19 2018 - 14:39" , 
    DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , Locale.US )
)                                      // Returns a `LocalDateTime` object.
.toLocalTime()                         // Extract a time-of-day value.
.toString()                            // Generate a String in standard ISO 8601 format.

14:39

java.time

The modern approach uses the java.time classes.

Define a formatting pattern to match your input. Specify Locale to determine human language and cultural norms used in parsing this localized input string.

String input = "Mar 19 2018 - 14:39" ;
Locale locale = Locale.US ;  // Specify `Locale` to determine human language and cultural norms used in parsing this localized input string.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM dd uuuu - HH:mm" , locale ) ;

Parse as a LocalDateTime because the input lacks any indicator of time zone or offset-from-UTC.

LocalDateTime ldt = LocalDateTime.parse( input , f  );

Extract the time-of-day value, without a date and without a time zone, as that is the goal of the Question.

LocalTime lt = ldt.toLocalTime();

ldt.toString(): 2018-03-19T14:39

lt.toString(): 14:39

ISO 8601

The format of your input is terrible. When serializing date-time values as text, always use standard ISO 8601 formats.

The java.time classes use the standard ISO 8601 formats by default when parsing/generating strings. You can see examples above in this Answer.


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.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

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

If you can use an external library, the Apache Common DateUtils provides many utility classes that you can use to work on dates. In order to parse your string to an object you can use for instance:

public static Date parseDate(String str, Locale locale, String... parsePatterns) throws ParseException

Parses a string representing a date by trying a variety of different parsers, using the default date format symbols for the given locale.

The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

The parser will be lenient toward the parsed date.

Parameters:str - the date to parse, not nulllocale - the locale whose date format symbols should be used. If null, the system locale is used (as per parseDate(String, String...)).parsePatterns - the date format patterns to use, see SimpleDateFormat, not nullReturns:the parsed dateThrows:IllegalArgumentException - if the date string or pattern array is nullParseException - if none of the date patterns were suitable (or there were none)Since:3.2

AR1
  • 4,507
  • 4
  • 26
  • 42