把格式为类如2017-01-30 1:30 PM 转化成24小时的格式

package com.tsing.weather;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class test {

    public static void main(String[] args) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm a",Locale.US);
        SimpleDateFormat format_1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String time = "2017-01-30 1:30 PM";
        try {
            Date d = format.parse(time);
            System.out.println(format_1.format(d));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

参考链接:https://my.oschina.net/u/928852/blog/100146

好的,我可以帮你写一个C++程序来实现这个功能,并且处理用户输入的非法时间。下面是代码,希望能够帮到你: ```cpp #include <iostream> #include <string> #include <regex> using namespace std; class time_mistake : public exception { public: const char* what() const throw() { return "非法时间格式!"; } }; string convertTimeFormat(string time) { regex pattern("([0-9]{2}):([0-9]{2})"); smatch match; regex_search(time, match, pattern); int hour = stoi(match[1]); int minute = stoi(match[2]); if (hour < 0 || hour > 23 || minute < 0 || minute > 59) { throw time_mistake(); } string suffix = hour < 12 ? "AM" : "PM"; hour = hour % 12; if (hour == 0) { hour = 12; } return to_string(hour) + ":" + match[2] + " " + suffix; } int main() { string time; cout << "请输入24小时时间格式(如:13:30):" << endl; cin >> time; try { string result = convertTimeFormat(time); cout << "12小时时间格式为:" << result << endl; } catch (time_mistake& e) { cerr << "Error: " << e.what() << endl; } return 0; } ``` 程序中定义了一个`time_mistake`异常类,用来处理用户输入的非法时间。在`convertTimeFormat`函数中,使用正则表达式提取输入字符串中的小时和分钟,并进行格式转换。如果输入时间不符合规范,将抛出`time_mistake`异常。在`main`函数中,捕获异常并输出错误信息,或者输出转换后的时间格式。 希望这个程序能够满足你的需求,如果还有其他问题,请随时提出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值