从我的一个Web服务方法调用返回浮点值的字符串:
Ex:375.677,61.47等。
我已经查看了堆栈交换问题并尝试了下面的解决方案。但那是返回无效值。这是我试过的代码:
float f = Float.parseFloat("375.677");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.add(Calendar.HOUR_OF_DAY, (int) f);
calendar.set(Calendar.MINUTE, (int) ((f * 60) % 60));
calendar.set(Calendar.SECOND, (int) ((f * 3600) % 3600));
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
System.out.println(dateFormat.format(calendar.getTime()));
请告诉我如何解决此问题。
提前致谢, 佐久
答案 0 :(得分:1)
只需要JDK 1.5。
String input = "375.677";
int mins = 0;
int secs = 0;
StringTokenizer st = new StringTokenizer(input, ".");
if (st.hasMoreTokens()) mins = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) secs = Integer.parseInt(st.nextToken());
if (st.hasMoreTokens()) throw new IllegalStateException("Second dot not allowed!");
int seconds = mins*60+secs;
int ss = seconds % 60;
seconds = seconds / 60;
int mm = seconds % 60;
seconds = seconds / 60;
int hh = seconds;
System.out.println(String.format("%02d:%02d:%02d", hh, mm, ss));
答案 1 :(得分:0)
我猜你的意思是指在该点之前的几分钟,以及它之后的几秒钟,其中分钟数达到931秒,秒数达到500.如果是,请尝试
float f = Float.parseFloat("375.677");
int m = ((int) f);
int s = ((int) (f * 1000)) % 1000;
// handle second overflow
m += s / 60;
s %= 60;
// handle minute overflow
int h = m / 60;
m %= 60;
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.HOUR_OF_DAY, h);
calendar.set(Calendar.MINUTE, m);
calendar.set(Calendar.SECOND, s);
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
System.out.println(dateFormat.format(calendar.getTime()));
答案 2 :(得分:0)
将所有内容转换为秒:
String timeString = "234.34";
String[] timeValuesAfterSplit = timeString.split("\\.");
int minutesToSeconds = Integer.parseInt(timeValuesAfterSplit[0]) * 60;
int totalSeconds = minutesToSeconds + Integer.parseInt(timeValuesAfterSplit[1]);
现在使用LocalTime获取给定格式的时间:
LocalTime localTime = LocalTime.ofSecondOfDay(totalSeconds);
然后,可以通过toString()
上的localTime
来获取您需要的格式。