用Java取指定时区的时间 北京时间,纽约时间,班加罗尔时间

复制代码
    /**
     * 取北京时间
     * @return
     */
    public static String getBeijingTime(){
        return getFormatedDateString(8);
    }
    
    /**
     * 取班加罗尔时间
     * @return
     */
    public static String getBangaloreTime(){
        return getFormatedDateString(5.5f);
    }
    
    /**
     * 取纽约时间
     * @return
     */
    public static String getNewyorkTime(){
        return getFormatedDateString(-5);
    }
    
    /**
* 此函数非原创,从网上搜索而来,timeZoneOffset原为int类型,为班加罗尔调整成float类型
* timeZoneOffset表示时区,如中国一般使用东八区,因此timeZoneOffset就是8 * @param timeZoneOffset * @return */ public static String getFormatedDateString(float timeZoneOffset){ if (timeZoneOffset > 13 || timeZoneOffset < -12) { timeZoneOffset = 0; } int newTime=(int)(timeZoneOffset * 60 * 60 * 1000); TimeZone timeZone; String[] ids = TimeZone.getAvailableIDs(newTime); if (ids.length == 0) { timeZone = TimeZone.getDefault(); } else { timeZone = new SimpleTimeZone(newTime, ids[0]); } SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.setTimeZone(timeZone); return sdf.format(new Date()); }
复制代码

 

posted @   逆火狂飙  阅读(11588)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
生当作人杰 死亦为鬼雄 至今思项羽 不肯过江东
点击右上角即可分享
微信分享提示