[java] Convert Java string to Time, NOT Date

I would like to convert a variable string to a Time type variable, not Date using Java. the string look like this 17:40

I tried using the code below but this instance is a date type variable not time

String fajr_prayertime  =       prayerTimes.get(0);
DateFormat formatter = new SimpleDateFormat("HH:mm");
fajr_begins = (Date)formatter.parse(fajr_prayertime);
System.out.println(" fajr time " + fajr_begins);

However Netbean complains that I should insert an exception as below;

DateFormat formatter = new SimpleDateFormat("HH:mm");
try {
fajr_begins = (Date)formatter.parse(fajr_prayertime);
} catch (ParseException ex) {
Logger.getLogger(JavaFXApplication4.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(" fajr time " + fajr_begins);

Any idea how I can get the time out of the string above.

This question is related to java string date time

The answer is


You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.

Example code in Joda-Time 2.7/Java 8.

LocalTime t = LocalTime.parse( "17:40" ) ;

try...

 java.sql.Time.valueOf("10:30:54");

try {

    SimpleDateFormat format = new SimpleDateFormat("hh:mm a"); //if 24 hour format
    // or
    SimpleDateFormat format = new SimpleDateFormat("HH:mm"); // 12 hour format

    java.util.Date d1 =(java.util.Date)format.parse(your_Time);

    java.sql.Time ppstime = new java.sql.Time(d1.getTime());

} catch(Exception e) {

    Log.e("Exception is ", e.toString());
}

String to Time (using an arbitrary time):

String myTime = "10:00:00"; 
Time startingTime = new Time (myTime);

String to Time (using currentTime):

String currentTime = getCurrentTime(); 
Time startingTime = new Time (currentTime);

Time to String:

private String getCurrentTime() {    
    SimpleDateFormat dateFormat = new SimpleDateFormat("kkmmss");
    String currentTime = dateFormat.format(System.currentTimeMillis());
    return currentTime;
}

You might want to take a look at this example:

public static void main(String[] args) {

    String myTime = "10:30:54";
    SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
    Date date = null;
    try {
        date = sdf.parse(myTime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedTime = sdf.format(date);

    System.out.println(formattedTime);

}

You can use the following code for changing the String value into the time equivalent:

 String str = "08:03:10 pm";
 DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
 Date date = (Date)formatter.parse(str);

Hope this helps you.


SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:MM");
simpleDateFormat.format(fajr_prayertime);

Joda-Time & java.time

Both Joda-Time and java.time (new in Java 8) offer a LocalTime class to represent a time-of-day without any date or time zone.

Example code, identical code for both java.time and Joda-Time.

LocalTime localTime = new LocalTime( "14:40" );
LocalTime deadline = new LocalTime( "15:30" );
boolean meetsDeadline = localTime.isBefore( deadline );

enter image description here


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.

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

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

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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to time

Date to milliseconds and back to date in Swift How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime how to sort pandas dataframe from one column Convert time.Time to string How to get current time in python and break up into year, month, day, hour, minute? Xcode swift am/pm time to 24 hour format How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time? What does this format means T00:00:00.000Z? How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift? Extract time from moment js object