simpleDateFormat 和 TimeZone

来源:互联网 发布:mac系统网游加速器 编辑:程序博客网 时间:2024/06/13 20:48
  • simpleDateFormat用法
 public static String toLongTimeString(Date dt){        SimpleDateFormat myFmt=new SimpleDateFormat("HH mm ss SSSS");                return myFmt.format(dt);    }
  • 1、通过改变默认的时区
TimeZone.setDefault(TimeZone.getTimeZone("GMT+8:00"));SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");System.out.println(sdf.format(Calendar.getInstance()));
  • 2、通过设定SimpleDateFormat的构造参数
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);System.out.println(sdf.format(new Date());
  • 1.影响TimeZone的因素:
    • 1.操作系统的时区设置。
    • 2.数据传输时时区设置。
  • 2.如何设置时区
public static void main(String[] args) {  SimpleDateFormat f1 = new SimpleDateFormat("yyyy-MM-dd");  try {    System.out.println(f1.parse("2015-12-12"));    f1.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));    System.out.println(f1.parse("2015-12-12"));  } catch (ParseException e) {    e.printStackTrace();  }}
  • 3.时区值大全
 {"ACT", "Australia/Darwin"}, {"AET", "Australia/Sydney"}, {"AGT", "America/Argentina/Buenos_Aires"}, {"ART", "Africa/Cairo"}, {"AST", "America/Anchorage"}, {"BET", "America/Sao_Paulo"}, {"BST", "Asia/Dhaka"}, {"CAT", "Africa/Harare"}, {"CNT", "America/St_Johns"}, {"CST", "America/Chicago"}, {"CTT", "Asia/Shanghai"}, {"EAT", "Africa/Addis_Ababa"}, {"ECT", "Europe/Paris"}, {"EST", "America/New_York"}, {"HST", "Pacific/Honolulu"}, {"IET", "America/Indianapolis"}, {"IST", "Asia/Calcutta"}, {"JST", "Asia/Tokyo"}, {"MIT", "Pacific/Apia"}, {"MST", "America/Denver"}, {"NET", "Asia/Yerevan"}, {"NST", "Pacific/Auckland"}, {"PLT", "Asia/Karachi"}, {"PNT", "America/Phoenix"}, {"PRT", "America/Puerto_Rico"}, {"PST", "America/Los_Angeles"}, {"SST", "Pacific/Guadalcanal"}, {"VST", "Asia/Saigon"}

TimeZone时区

  • 1.获取默认的TimeZone对象
TimeZone tz = TimeZone.getDefault()
  • 2..使用 getTimeZone(String id) 方法获取TimeZone对象
// 获取 “GMT+08:00”对应的时区TimeZone china = TimeZone.getTimeZone("GMT+:08:00");// 获取 “中国/重庆”对应的时区TimeZone chongqing = TimeZone.getTimeZone("Asia/Chongqing");
  • 3.TimeZone示列
import java.text.DateFormat;import java.util.Date;import java.util.TimeZone;/** * TimeZone的测试程序 */public class TimeZoneTest { public static void main(String[] args) { // 测试创建TimeZone对象的3种方法 showUsageOfTimeZones() ; // 测试TimeZone的其它API testOtherAPIs() ; // 打印getTimeZone(String id)支持的所有id //printAllTimeZones() ; } /** * 测试创建TimeZone对象的3种方法 */ public static void showUsageOfTimeZones() { TimeZone tz; // (01) 默认时区 tz = TimeZone.getDefault(); printDateIn(tz) ; // (02) 设置时区为"GMT+08:00" tz = TimeZone.getTimeZone("GMT+08:00"); printDateIn(tz) ; // (03) 设置时区为"" tz = TimeZone.getTimeZone("Asia/Chongqing"); printDateIn(tz) ; } /** * 打印 tz对应的日期/时间 */ private static void printDateIn(TimeZone tz) { // date为2013-09-19 14:22:30 Date date = new Date(113, 8, 19, 14, 22, 30); // 获取默认的DateFormat,用于格式化Date DateFormat df = DateFormat.getInstance(); // 设置时区为tz df.setTimeZone(tz); // 获取格式化后的字符串 String str = df.format(date); System.out.println(tz.getID()+" :"+str); } /** * 测试TimeZone的其它API */ public static void testOtherAPIs() { // 默认时区 TimeZone tz = TimeZone.getDefault(); // 获取“id” String id = tz.getID(); // 获取“显示名称” String name = tz.getDisplayName(); // 获取“时间偏移”。相对于“本初子午线”的偏移,单位是ms。 int offset = tz.getRawOffset(); // 获取“时间偏移” 对应的小时 int gmt = offset/(3600*1000); System.out.printf("id=%s, name=%s, offset=%s(ms), gmt=%s\n",  id, name, offset, gmt); } /** * 打印getTimeZone(String id)支持的所有id */ public static void printAllTimeZones() { String[] ids = TimeZone.getAvailableIDs(); for (String id:ids) {  //int offset = TimeZone.getTimeZone(avaIds[i]).getRawOffset();  //System.out.println(i+" "+avaIds[i]+" "+offset / (3600 * 1000) + "\t");  System.out.printf(id+", "); } System.out.println(); }}

java.util.TimeZone.getOffset()方法实例

  • getOffset(int era,int year,int month,int day,int dayOfWeek,int milliseconds) 方法用于获取时区偏移量,为当前日期,修改夏令时情况下。这是偏移量添加到UTC以获取本地时间。
  • 参数

    • era–这是给定日期的年代。
    • year–这是给定日期的年份。
    • month–这是给定日期的月份。
    • day–这是一天中个月的特定日期。
    • dayOfWeek–这是给定日期的周的一天。
    • milliseconds–这是在一天的毫秒标准的本地时间。
  • 返回值

    • 方法调用返回偏移量,单位为毫秒添加到GMT以获取本地时间。
  • eg:
public class TimeZoneDemo {   public static void main( String args[] ){      // create time zone object           TimeZone timezone = TimeZone.getTimeZone("Europe/Paris");      // checking offset value             System.out.println("Offset value is :" + timezone.getOffset(1, 2011, 2, 2, 2, 300));   }    }

本地时间,LocalTime

  • LocalTime是值类型,且跟日期和时区没有关联。当我们对时间进行加减操作时,以午夜基准,24小时一个周期。因此,20:00加上6小时,结果就是02:00。
  • LocalTime的用法跟LocalDate相似:
LocalTime time = LocalTime.of(20, 30);int hour = date.getHour(); // 20int minute = date.getMinute(); // 30time = time.withSecond(6); // 20:30:06time = time.plusMinutes(3); // 20:33:06

时间和日期组合LocalDateTime

  • LocalDateTime可以直接创建,或者组合时间和日期:
LocalDateTime dt1 = LocalDateTime.of(2014, Month.JUNE, 10, 20, 30);LocalDateTime dt2 = LocalDateTime.of(date, time);LocalDateTime dt3 = date.atTime(20, 30);LocalDateTime dt4 = date.atTime(time);
  • ZoneDateTime负责处理面向人类的(台历和挂钟上看到的)时间和面向机器的时间(始终连续增长的秒数)之间的转换。因此,你可以通过本地时间或时间点来创建ZoneDateTime实例:
ZoneId zone = ZoneId.of("Europe/Paris");LocalDate date = LocalDate.of(2014, Month.JUNE, 10);ZonedDateTime zdt1 = date.atStartOfDay(zone);Instant instant = Instant.now();ZonedDateTime zdt2 = instant.atZone(zone);

转载

/**     * 根据给定的时间返回对应格式的字符串     *  1、小于一分钟---"刚刚"     *  2、大于一分钟而在本日内的,返回格式为"HH:mm"     *  3、今年之内而不再本日内,格式为"MM-dd"     *  4、否则,格式为"yyyy-MM-dd"     * @param strDate     * @return     */    public static String getFormatDate(String strDate) {        DateTimeFormatter formatter;        ZonedDateTime zonedDateTime = ZonedDateTime.parse(strDate);        if (zonedDateTime.toLocalDate().equals(LocalDate.now())) {            if (getOverMinutes(strDate) <= 1) {                return "刚刚";            } else {                formatter = DateTimeFormatter.ofPattern("HH:mm", Locale.CHINA);                return zonedDateTime.format(formatter);            }        } else {            if (zonedDateTime.toLocalDate().getYear() == LocalDate.now().getYear()) {                formatter = DateTimeFormatter.ofPattern("MM-dd", Locale.CHINA);            } else {                formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.CHINA);            }            return zonedDateTime.format(formatter);        }    }    /**     * 将给定的秒数转换为一段持续时间,如70s,可为01:10     * @param s     * @return     */    public static String sec2Duration(int s) {        int sec;        if (s < 0) {            return "00:00";        }        int min = s / 60;        if (min < 60) {            sec = s % 60;            return unitFormat(min) + ":" + unitFormat(sec);        } else {            int hour = min / 60;            min = min % 60;            sec = s - hour * 3600 - min * 60;            return unitFormat(hour) + ":" + unitFormat(min) + ":" + unitFormat(sec);        }    }    public static String unitFormat(int i) {        return i >= 0 && i < 10 ? "0" + i : i + "";    }    /**     * 给定开始时间,返回还剩多少天多少时多少分的字符串数组     * @param startTime     * @return     */    public static String[] getLeftStr(String startTime) {        Instant start = ZonedDateTime.parse(startTime).toInstant();        long minutes = Duration.between(Instant.now(), start).toMinutes();        if (minutes < 60 && minutes > 0) {            return new String[]{"0", "0", minutes + ""};        } else if (minutes <= 0) {            return null;        }        long hours = minutes / 60;        if (hours < 60) {            minutes = minutes % 60;            return new String[]{"0", hours + "", minutes + ""};        } else {            long days = hours / 24;            hours = hours % 24;            minutes = minutes - days * 24 * 60 - hours * 60;            return new String[]{days + "", hours + "", minutes + ""};        }    }    /**     * 根据创建时间和总共时间得到当前剩余时间     * @param createStr     * @param totalMills     * @return     */    public static long getLeftMills(String createStr, long totalMills) {        long leftMills = totalMills - getOverMills(createStr);        return leftMills >= 0 ? leftMills : 0;    }    public static long getLeftMinutes(String createStr, long totalMinutes) {        long leftMinutes = totalMinutes - getOverMinutes(createStr);        return leftMinutes >= 0 ? leftMinutes : 0;    }    public static long getLeftHours(String createStr, long totalHours) {        long leftHours = totalHours - getOverHours(createStr);        return leftHours >= 0 ? leftHours : 0;    }    /**     * 根据跟定的时间得到到目前为止过了多少秒     * @param time     * @return     */    public static long getOverMills(String time){        return getOverTime(time).toMillis();    }    public static long getOverMinutes(String time){        return getOverTime(time).toMinutes();    }    public static long getOverHours(String time){        return getOverTime(time).toHours();    }    private static Duration getOverTime(String time) {        Instant timeInstant = ZonedDateTime.parse(time).toInstant();        Instant now = Instant.now();        return Duration.between(timeInstant, now);    }    /**     * 将UNIX时间戳(秒级)格式化成ZoneDateTime的格式     */    public static String format2ZoneDateTimeFromSecond(long timestamp) {        return ZonedDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.of("Asia/Shanghai")).toString();    }
原创粉丝点击