如何在Android中将结束时间获取为浮点数。

huangapple go评论79阅读模式
英文:

How to get end time as float in Android

问题

I had a String time format like 08:25 now how can I convert to float time value

String guestclosetime = getCurrentTime();
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {

    System.out.println("starttime" + TestRideFragment.getCurrentTime());
    // convert12to24format(guestclosetime);
    Date date1 = timeFormat.parse("00:20");//run
    Date date2 = timeFormat.parse(guestclosetime);
    //Date date3=timeFormat.parse(idle_time);

    long sum = date1.getTime() + date2.getTime();

    String date3 = timeFormat.format(new Date(sum));
    System.out.println("The sum is " + date3);// 08:28

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that
英文:

I had a String time format like 08:25 now how can I convert to float time value

    String guestclosetime = getCurrentTime();
    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");

    timeFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    try {

        System.out.println("starttime"+ TestRideFragment.getCurrentTime());
        // convert12to24format(guestclosetime);
        Date date1 = timeFormat.parse("00:20");//run
        Date date2 = timeFormat.parse(guestclosetime);
        //Date date3=timeFormat.parse(idle_time);

        long sum = date1.getTime() + date2.getTime();

        String date3 = timeFormat.format(new Date(sum));
        System.out.println("The sum is "+date3);// 08:28

now I need the date3 as float how can I do in android.

see I had a scenario as a driver drops a person at x place here I get the current time like 08:30 AM. and after dropping he needs to reach his destination and he took 20 mins this is in float need to convert as a string and if we add this 2 we need to get the total time as 08:50 now this total time need to save as float

I need like 1.30 = 1.5 like that

答案1

得分: 1

## java.time 和 ThreeTenABP

我建议您使用 `java.time`,这是现代的 Java 日期和时间 API,来进行时间计算。您不能使用 `Date` 来表示一段时间。而是可以使用 `LocalTime` 表示一天中的某个时间,使用 `Duration` 表示持续时间,即一段时间的长度。

```java
LocalTime dropOff = LocalTime.of(8, 30);
System.out.println("Drop-off: " + dropOff);

Duration timeToDest = Duration.ofMinutes(20);
LocalTime end = dropOff.plus(timeToDest);
System.out.println("Time at destination: " + end);

输出:

>     Drop-off: 08:30
>     Time at destination: 08:50

要转换为表示自午夜以来的小时数的 float

float hoursSinceMidnight = (float) end.getLong(ChronoField.NANO_OF_DAY)
        / (float) Duration.ofHours(1).toNanos();
System.out.println("As float: " + hoursSinceMidnight);
>     As float: 8.833334

问题:java.time 不是需要 Android API 等级 26 吗?

java.time 在旧版本和新版本的 Android 设备上都可以很好地工作。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及较新的 Android 设备(从 API 等级 26 开始),这个现代 API 已经内置。
  • 在非 Android 环境中,Java 6 和 7 可以使用 ThreeTen Backport,这是现代类的后移版本(ThreeTen for JSR 310)。在底部的链接中可以找到更多信息。
  • 在(较旧的) Android 设备上,请使用 ThreeTenABP 的 Android 版本。它被称为 ThreeTenABP。并且确保从 org.threeten.bp 及其子包中导入日期和时间类。

链接


<details>
<summary>英文:</summary>

## java.time and ThreeTenABP

I recommend that you use java.time, the modern Java date and time API, for your time math. You cannot use a `Date` for an amount of time. Instead use `LocalTime` for a time of day and `Duration` for a duration, an amount of time.

		LocalTime dropOff = LocalTime.of(8, 30);
		System.out.println(&quot;Drop-off: &quot; + dropOff);
		
		Duration timeToDest = Duration.ofMinutes(20);
		LocalTime end = dropOff.plus(timeToDest);
		System.out.println(&quot;Time at destination: &quot; + end);

Output:

&gt;     Drop-off: 08:30
&gt;     Time at destination: 08:50

To convert to a `flaot` indicating the number of hours since midnight:

		float hoursSinceMidnight = (float) end.getLong(ChronoField.NANO_OF_DAY)
				/ (float) Duration.ofHours(1).toNanos();
		System.out.println(&quot;As float: &quot; + hoursSinceMidnight);

&gt;     As float: 8.833334

## Question: Doesn’t java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least **Java 6**.

 - In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
 - In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
 - On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from `org.threeten.bp` with subpackages.

## Links

 - [Oracle tutorial: Date Time](https://docs.oracle.com/javase/tutorial/datetime/) explaining how to use java.time.
 - [Java Specification Request (JSR) 310](https://jcp.org/en/jsr/detail?id=310), where `java.time` was first described.
 - [ThreeTen Backport project](http://www.threeten.org/threetenbp/), the backport of `java.time` to Java 6 and 7 (ThreeTen for JSR-310).
 - [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP), Android edition of ThreeTen Backport
 - [Question: How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project), with a very thorough explanation.

</details>



# 答案2
**得分**: 0

这里

    String date3 = timeFormat.format(new Date(sum));
    // 首先,您必须将&quot;:&quot;替换为&quot;.&quot;,以获取可以转换为浮点数的有效字符串
    String strDate = date3.replace(&quot;:&quot;, &quot;.&quot;);
    // 使用Float.valueOf()进行转换
    Float floatValue = Float.valueOf(strDate);

<details>
<summary>英文:</summary>

Here

    String date3 = timeFormat.format(new Date(sum));
    // First you have to replace &quot;:&quot; to &quot;.&quot; to get valid string that can be converted to float
    String strDate = date3.replace(&quot;:&quot;, &quot;.&quot;);
    // Use Float.value() to convert
    Float floatValue = Float.valueOf(strDate);
      

   

</details>



# 答案3
**得分**: 0

```java
public static float HoursToFloat(String tmpHours) {
    float result = 0;
    tmpHours = tmpHours.trim();
    try {
        result = new Float(tmpHours);
    } catch (NumberFormatException nfe) {

        if (tmpHours.contains(":")) {
            int hours = 0;
            float minutes = 0;
            try {
                hours = Integer.parseInt(tmpHours.split(":")[0]);
                minutes = Integer.parseInt(tmpHours.split(":")[1]);
            } catch (Exception nfe2) {
                throw nfe2;
            }

            if (minutes > 0) {
                result = minutes / 60;
            }
            result += hours;
        }
    }
    return result;
}
英文:

Is that your goal?

"1:30" => 1.5 "1.83" => 1.83 "0.5" => 0.5

If you try it right

public static float HoursToFloat(String tmpHours)  {
    float result = 0;
    tmpHours = tmpHours.trim();
    try {
        result = new Float(tmpHours);
    } catch (NumberFormatException nfe) {

        if (tmpHours.contains(&quot;:&quot;)) {
            int hours = 0;
            float minutes = 0; 
            try {
                hours = Integer.parseInt(tmpHours.split(&quot;:&quot;)[0]);
                minutes = Integer.parseInt(tmpHours.split(&quot;:&quot;)[1]); 
            } catch (Exception nfe2) {
                throw nfe2;
            }

            if (minutes &gt; 0) {
                result = minutes / 60;
            }
            result += hours;
        }
    }
    return result;
}

huangapple
  • 本文由 发表于 2020年5月30日 10:44:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/62097188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定