解析Java / GWT中的用户时间输入 [英] Parsing user time input in Java/GWT

查看:104
本文介绍了解析Java / GWT中的用户时间输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析用户在GWT文本字段中键入的时间的最佳方式是什么?默认时间格式要求用户输入时间与locale的时间格式指定时间完全一致。

What is the best way to parse time that a user typed in a text field in GWT? Default time formats require users to enter time exactly as the time format for locale specifies it.

我想要更灵活,因为用户可以输入多种不同的时间。例如,8,8p,8pm,8.15pm,13:15,1315,13.15等条目应该是有效的。

I want to be more flexible as there are many different ways users can enter time. For example, entries like "8", "8p", "8pm", "8.15pm", "13:15", "1315", "13.15" should be valid.

推荐答案

我结束了自己想分享的方法。此方法返回以毫秒为单位的时间,可以使用所选语言环境的任何数据格式显示。

I ended up with my own method that I want to share. This method returns time in milliseconds, which can be displayed using any data formats for the selected locale.

任何有待改进的建议都将得到高度赞赏。

Any suggestions to improve it are highly appreciated.

编辑:改进了以下评论建议。

Improved following suggestions in comments.

public static Long parseTime(String value) {

    // ";" is a common typo - we are not punishing users for it
    value = value.trim().toLowerCase().replace(";", ":");

    RegExp time12 = RegExp.compile("^(1[012]|[1-9])([:.][0-5][0-9])?(\\s)?(a|p|am|pm)?$");
    RegExp time24 = RegExp.compile("^(([01]?[0-9]|2[0-3])[:.]?([0-5][0-9])?)$");

    if (time12.test(value) || time24.test(value)) {

        String hours = "0", minutes = "0";

        if (value.contains(":") || value.contains(".")) {
            String[] values = value.split("[:.]");
            hours =  values[0];
            minutes = values[1].substring(0, 2);
        } else {
            // Process strings like "8", "8p", "8pm", "2300"
            if (value.contains("a")) {
                hours = value.substring(0, value.indexOf("a")).trim();
            } else if (value.contains("p")) {
                hours = value.substring(0, value.indexOf("p")).trim();
            } else if (value.length() < 3) {
                hours = value;
            } else {
                hours =  value.substring(0, value.length() - 2);
                minutes = value.substring(value.length() - 2);
            }
        }
        if (value.contains("a") && hours.equals("12")) {
            // 12am is actually zero hours
            hours = "0";
        }

        Long time = (Long.valueOf(hours) * 60 + Long.valueOf(minutes)) * 60 * 1000;

        if (value.contains("p") && !hours.equals("12")) {
            // "pm" adds 12 hours to the total, except for 12pm
            time += 12 * 60 * 60 * 1000;
        }

        return time;
    }
    return null;
}

这篇关于解析Java / GWT中的用户时间输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆