安卓 配合Shell命令使用的, 获取网络时间, 加减分钟的静态类


/**
 * @author HuWT
 */
public class TimeTool {
    private static final String TAG = "TimeTool";
    // 从淘宝网获取时间
    private static final String TIME_URL = "http://www.taobao.com";
    private static Date date;
    

    /**
     * 将 TimeTool.date表示的时间加上 minutes分钟
     * @param minutes
     * @return 通过 getStrDate()返回一个可以被Shell命令解析的日期字符串
     */
    public static String getLocalTimeAdd(long minutes){
        if (TimeTool.date == null){
            Log.i(TAG, "getLocalTimeAdd: \n***** 请在使用本方法前,确保TimeTool.date != null");
            return null;
        }
        long ms = minutes * 60 * 1000;

        // 下行中的date可以换成 System.currentTimeMillis() 来确保Time.date != null
        /* 这里使用 TimeTool.date 是项目要求的.所以, 准确的来说,
         * 本方法是对最近获取的网络时间进行加减
         */
        long newMS = (Long.valueOf(date.getTime())+ms);
        return getStrDate(new Date(newMS));
    }


    /**
     * 获取最新的网络时间, 并将时间保存到 TimeTool.date
     * @return
     */
    public static String getNetDate() {
        // 更新 TimeTool.date
        getDatefrom();

        Date temp = TimeTool.date;
        while (TimeTool.date == temp) {
            sleep(500);
            Log.d(TAG, "getNetDate: 正在等待TimeTool.date更新...");
        }

        return getStrDate(TimeTool.date);
    }

    /**
     * 从网络上获取时间, 并将时间保存到 TimeTool.date
     */
    private static void getDatefrom() {
        new Thread() {
            @Override
            public void run() {
                URL url = null;
                try {
                    url = new URL(TIME_URL);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }

                //生成连接对象
                URLConnection uc = null;
                try {
                    uc = url.openConnection();
                    //发出连接
                    uc.connect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //取得网站日期时间
                long ld = uc.getDate();
                //转换为标准时间对象
                TimeTool.date = new Date(ld);
            }
        }.start();
    }

    /**
     * 将 Date 类型转换为 Shell  date -s命令可以使用的 字符型格式
     * @param date
     * @return
     */
    static String getStrDate(Date date){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd.HHmmss");
        return sdf.format(date);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值