简体   繁体   中英

How do I convert "HH:MM" format string to Timestamp in Java?

I have a string 09:28. and I want to convert this string to Timestamp object.

Below is my coding:

Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant.DAT_STOPDATE);
Date stopDate1 = (Date)d;
SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm");
String timeString = printFormat.format(stopDate1);

Now I want above String as Timestamp (only HH:MM). How to do that?

Please Use parse method to get Date Object and then construct Timestamp object.

 try {
    Timestamp timestamp = new Timestamp(printFormat.parse(timeString).getTime());
    } catch (ParseException e) {
        e.printStackTrace();
    }

You can use LocalTime to store times (from a string and vice-versa) as shown below:

Option(1): With Java8

You can use Java8's LocalTime API for this, you can look here

String timeString = printFormat.format(stopDate1);
//Get your localTime object from timeString
LocalTime localTime = LocalTime.parse(timeString);

static LocalTime parse(CharSequence text) Obtains an instance of LocalTime from a text string such as 10:15.

Option(2): Without Java8

You need to use jodatime library API, you can look here

Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]

You can convert date object to Timestamp directly by

 Timestamp timestamp = new Timestamp(stopDate1.getTime());

if you are looking for the timestamp of today's hh:mm then try this

static String todaysFtoTimestamp(String f){
    long todaystimestamp = ((System.currentTimeMillis() / 86400000 )  * 86400 );
    //System.out.println("today: " + todaystimestamp);
    long todaysftimestamp = Integer.parseInt(fToTimestamp(f)) + todaystimestamp;
    //System.out.println("todayF: " + todaysftimestamp);
    return todaysftimestamp+"";
}
static String fToTimestamp(String f){
    String[] fArray = f.split(":");
    String r = "null hehe";
    int hours = Integer.parseInt(fArray[0]);
    int minutes = Integer.parseInt(fArray[1]);
    r = String.valueOf((minutes + (hours * 60))*60);
    return r ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM