[英]How do I convert "HH:MM" format string to Timestamp in Java?
我有一个字符串09:28.
我想将此字符串转换为Timestamp
对象。
下面是我的编码:
Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant.DAT_STOPDATE);
Date stopDate1 = (Date)d;
SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm");
String timeString = printFormat.format(stopDate1);
现在我想要上面的String
作为Timestamp
(仅 HH:MM)。 怎么做?
请使用parse方法获取Date对象,然后构造Timestamp对象。
try {
Timestamp timestamp = new Timestamp(printFormat.parse(timeString).getTime());
} catch (ParseException e) {
e.printStackTrace();
}
您可以使用LocalTime存储时间(从字符串开始,反之亦然),如下所示:
选项(1):使用Java8
您可以为此使用Java8的LocalTime API,可以在此处查看
String timeString = printFormat.format(stopDate1);
//Get your localTime object from timeString
LocalTime localTime = LocalTime.parse(timeString);
static LocalTime parse(CharSequence text)从文本字符串(例如10:15)获取LocalTime的实例。
选项(2):没有Java8
您需要使用jodatime库API,可以在此处查看
时间戳记格式必须为yyyy-mm-dd hh:mm:ss [.fffffffff]
您可以直接通过以下方式将日期对象转换为时间戳
Timestamp timestamp = new Timestamp(stopDate1.getTime());
如果您正在寻找今天 hh:mm 的时间戳,那么试试这个
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 ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.