精华内容
下载资源
问答
  • java当前时间获取

    万次阅读 2020-01-16 21:11:29
    接着源码阅读:new Date之旅,补充几种关于获取当前时间的方式。 Date 在Java中,获取当前日期最简单的方法之一就是直接实例化位于Javajava.util的Date类。 Date date = new Date(); System.currentTimeMillis ...

    前言

    接着源码阅读:new Date之旅,补充几种关于获取当前时间的方式。

    Date

    在Java中,获取当前日期最简单的方法之一就是直接实例化位于Java包java.util的Date类。

    Date date = new Date();
    

    System.currentTimeMillis

    获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响,得到的结果是时间戳格式的。

    long time = System.currentTimeMillis();
    

    源码:

    	 /**
         * Returns the current time in milliseconds.  Note that
         * while the unit of time of the return value is a millisecond,
         * the granularity of the value depends on the underlying
         * operating system and may be larger.  For example, many
         * operating systems measure time in units of tens of
         * milliseconds.
         *
         * <p> See the description of the class <code>Date</code> for
         * a discussion of slight discrepancies that may arise between
         * "computer time" and coordinated universal time (UTC).
         *
         * @return  the difference, measured in milliseconds, between
         *          the current time and midnight, January 1, 1970 UTC.
         * @see     java.util.Date
         */
        public static native long currentTimeMillis();
    

    Calendar

    Calendar类,专门用于转换特定时刻和日历字段之间的日期和时间。

    Calendar calendar = Calendar.getInstance(); 
    

    源码:

    /**
         * Gets a calendar using the default time zone and locale. The
         * <code>Calendar</code> returned is based on the current time
         * in the default time zone with the default
         * {@link Locale.Category#FORMAT FORMAT} locale.
         *
         * @return a Calendar.
         */
        public static Calendar getInstance()
        {
            return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
        }
    
       	private static Calendar createCalendar(TimeZone zone,
                                               Locale aLocale)
        {
            CalendarProvider provider =
                LocaleProviderAdapter.getAdapter(CalendarProvider.class, aLocale)
                                     .getCalendarProvider();
            if (provider != null) {
                try {
                    return provider.getInstance(zone, aLocale);
                } catch (IllegalArgumentException iae) {
                    // fall back to the default instantiation
                }
            }
    
            Calendar cal = null;
    
            if (aLocale.hasExtensions()) {
                String caltype = aLocale.getUnicodeLocaleType("ca");
                if (caltype != null) {
                    switch (caltype) {
                    case "buddhist":
                    cal = new BuddhistCalendar(zone, aLocale);
                        break;
                    case "japanese":
                        cal = new JapaneseImperialCalendar(zone, aLocale);
                        break;
                    case "gregory":
                        cal = new GregorianCalendar(zone, aLocale);
                        break;
                    }
                }
            }
            if (cal == null) {
                // If no known calendar type is explicitly specified,
                // perform the traditional way to create a Calendar:
                // create a BuddhistCalendar for th_TH locale,
                // a JapaneseImperialCalendar for ja_JP_JP locale, or
                // a GregorianCalendar for any other locales.
                // NOTE: The language, country and variant strings are interned.
                if (aLocale.getLanguage() == "th" && aLocale.getCountry() == "TH") {
                    cal = new BuddhistCalendar(zone, aLocale);
                } else if (aLocale.getVariant() == "JP" && aLocale.getLanguage() == "ja"
                           && aLocale.getCountry() == "JP") {
                    cal = new JapaneseImperialCalendar(zone, aLocale);
                } else {
                    cal = new GregorianCalendar(zone, aLocale);
                }
            }
            return cal;
        }
    

    LocalDateTime

    LocalDateTime,是Java中最常用的Date / Time类,代表前两个类的组合 – 即日期和时间的值。

    LocalDateTime dateTime = LocalDateTime.now(); 
    

    源码:

    	 /**
         * Obtains the current date-time from the system clock in the default time-zone.
         * <p>
         * This will query the {@link Clock#systemDefaultZone() system clock} in the default
         * time-zone to obtain the current date-time.
         * <p>
         * Using this method will prevent the ability to use an alternate clock for testing
         * because the clock is hard-coded.
         *
         * @return the current date-time using the system clock and default time-zone, not null
         */
        public static LocalDateTime now() {
            return now(Clock.systemDefaultZone());
        }
      	/**
         * Obtains the current date-time from the specified clock.
         * <p>
         * This will query the specified clock to obtain the current date-time.
         * Using this method allows the use of an alternate clock for testing.
         * The alternate clock may be introduced using {@link Clock dependency injection}.
         *
         * @param clock  the clock to use, not null
         * @return the current date-time, not null
         */
        public static LocalDateTime now(Clock clock) {
            Objects.requireNonNull(clock, "clock");
            final Instant now = clock.instant();  // called once
            ZoneOffset offset = clock.getZone().getRules().getOffset(now);
            return ofEpochSecond(now.getEpochSecond(), now.getNano(), offset);
        }
     	 /**
         * Obtains an instance of {@code LocalDateTime} using seconds from the
         * epoch of 1970-01-01T00:00:00Z.
         * <p>
         * This allows the {@link ChronoField#INSTANT_SECONDS epoch-second} field
         * to be converted to a local date-time. This is primarily intended for
         * low-level conversions rather than general application usage.
         *
         * @param epochSecond  the number of seconds from the epoch of 1970-01-01T00:00:00Z
         * @param nanoOfSecond  the nanosecond within the second, from 0 to 999,999,999
         * @param offset  the zone offset, not null
         * @return the local date-time, not null
         * @throws DateTimeException if the result exceeds the supported range,
         *  or if the nano-of-second is invalid
         */
        public static LocalDateTime ofEpochSecond(long epochSecond, int nanoOfSecond, ZoneOffset offset) {
            Objects.requireNonNull(offset, "offset");
            NANO_OF_SECOND.checkValidValue(nanoOfSecond);
            long localSecond = epochSecond + offset.getTotalSeconds();  // overflow caught later
            long localEpochDay = Math.floorDiv(localSecond, SECONDS_PER_DAY);
            int secsOfDay = (int)Math.floorMod(localSecond, SECONDS_PER_DAY);
            LocalDate date = LocalDate.ofEpochDay(localEpochDay);
            LocalTime time = LocalTime.ofNanoOfDay(secsOfDay * NANOS_PER_SECOND + nanoOfSecond);
            return new LocalDateTime(date, time);
        }
    
    

    结果

    当前时间获取对比
    先赞后看,养成习惯。欢迎收看一个行走的熊猫程序猿,下期再见

    关注

    展开全文
  • Java 当前时间的上一个月时间、上一年时间 获取当前时间 /** * 获取当前时间 * @return Timestamp * @author zhangyao * date: 2018/8/22 11:36 */ public static Timestamp now() { return new Timestamp...

    Java 当前时间的上一个月时间、上一年时间

    • 获取当前时间
        /**
         * 获取当前时间
         * @return Timestamp
         * @author  zhangyao
         * date: 2018/8/22 11:36
         */
        public static Timestamp now() {
            return new Timestamp(Calendar.getInstance().getTimeInMillis());
        }
      
    • 上个月、上一年;time可以用获取当前时间的值
          /**
         * 上一个月
         */
        private Timestamp lastMonthTime(Timestamp time){
            Calendar c = Calendar.getInstance();
            c.setTime(time);
            c.add(Calendar.MONTH, -1);
            return  new Timestamp(c.getTimeInMillis());
        }
      
        private Timestamp lastYearTime(Timestamp time){
            //过去一年
            Calendar c = Calendar.getInstance();
            c.setTime(time);
            c.add(Calendar.YEAR, -1);
            return  new Timestamp(c.getTimeInMillis());
        }
      
    展开全文
  • java当前时间增加一小时怎么写

    千次阅读 2020-06-02 10:54:28
    获取java当前时间增加一小时怎么写 首先新建Date对象,然后转化成Calendar对象,利用其中的方法得到一小时后的Calendar对象,再转化成Date。 //设置创建时间 Date creatTime = new Date(); noteEatlyWarningInfo...

    获取java当前时间增加一小时怎么写

    首先新建Date对象,然后转化成Calendar对象,利用其中的方法得到一小时后的Calendar对象,再转化成Date。

    		//设置创建时间
            Date creatTime = new Date();
            noteEatlyWarningInfo.setCreatTime(creatTime);
            //设置生效时间为一小时后
            Calendar cal = Calendar.getInstance();
            cal.setTime(creatTime);
            cal.add(Calendar.HOUR, 1);// 24小时制
            Date effectivetime = cal.getTime();
            noteEatlyWarningInfo.setEffectiveTime(effectivetime);
    
    展开全文
  • 方法1:new SimpleDateFormat(“yyyyMMddHHmmssSSS”) .format(new Date() );方法2:new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss:... 获取当前系统时间和日期并格式化输出:import java.util.Date;import java.text....

    方法1:new SimpleDateFormat(“yyyyMMddHHmmssSSS”) .format(new Date() );

    方法2:new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss:SSS”) .format(new Date() );

    一. 获取当前系统时间和日期并格式化输出:

    import java.util.Date;

    import java.text.SimpleDateFormat;

    public class NowString {

    public static void main(String[] args) {

    SimpleDateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);//设置日期格式

    System.out.println(df.format(new Date()));// new Date()为获取当前系统时间

    }

    }

    二. 在数据库里的日期只以年-月-日的方式输出,可以用下面两种方法:

    1、用convert()转化函数:

    String sqlst = “select convert(varchar(10),bookDate,126) as convertBookDate from roomBook where bookDate between ’2007-4-10′ and ’2007-4-25′”;

    System.out.println(rs.getString(“convertBookDate”));

    2、利用SimpleDateFormat类:

    先要输入两个java包:

    import java.util.Date;

    import java.text.SimpleDateFormat;

    然后:

    定义日期格式:SimpleDateFormat sdf = new SimpleDateFormat(yy-MM-dd);

    sql语句为:String sqlStr = “select bookDate from roomBook where bookDate between ’2007-4-10′ and ’2007-4-25′”;

    输出:

    System.out.println(df.format(rs.getDate(“bookDate”)));

    ************************************************************

    java中获取当前日期和时间的方法

    import java.util.Date;

    import java.util.Calendar;

    import java.text.SimpleDateFormat;

    public class TestDate{

    public static void main(String[] args){

    Date now = new Date();

    SimpleDateFormat dateFormat = new SimpleDateFormat(“yyyy/MM/dd HH:mm:ss”);//可以方便地修改日期格式

    String hehe = dateFormat.format( now );

    System.out.println(hehe);

    Calendar c = Calendar.getInstance();//可以对每个时间域单独修改

    int year = c.get(Calendar.YEAR);

    int month = c.get(Calendar.MONTH);

    int date = c.get(Calendar.DATE);

    int hour = c.get(Calendar.HOUR_OF_DAY);

    int minute = c.get(Calendar.MINUTE);

    int second = c.get(Calendar.SECOND);

    System.out.println(year + “/” + month + “/” + date + ” ” +hour + “:” +minute + “:” + second);

    }

    }

    有时候要把String类型的时间转换为Date类型,通过以下的方式,就可以将你刚得到的时间字符串转换为Date类型了。

    SimpleDateFormat sdf=new SimpleDateFormat(“yyyy-MM-dd”);

    java.util.Date time=null;

    try {

    time= sdf.parse(sdf.format(new Date()));

    } catch (ParseException e) {

    e.printStackTrace();

    }

    展开全文
  • var myDate = new Date();... //获取当前年份(2位)myDate.getFullYear(); //获取完整的年份(4位,1970-????)myDate.getMonth(); //获取当前月份(0-11,0代表1月)myDate.getDate(); //获取当前日(1-31)myDate.getDa...
  • java 当前时间月份

    千次阅读 2019-01-26 17:05:00
    System.out.println("加了一个月之后,广告到期时间为:" + df.format(newDate)); } public static Date stepMonth(Date sourceDate, int month) { Calendar c = Calendar.getInstance(); c.setTime(sourceDate);...
  • 转发来源: ...utm_medium=referral获取当前时间戳//方法 一System.currentTimeMillis();//方法 二Calendar.getInstance().getTimeInMillis();//方法 三new Date()....
  • java 当前时间+1

    2015-12-09 15:15:46
    import java.util.Calendar; import java.util.Date; public class DateAddOne { ... * 设置当前时间加1 */ public static void main(String[] args) { Calendar c = Calendar.getInstance();
  • 如代码所示:SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");...System.out.println("当前时间:"+sdf.format(now));方法一:longtime=30*60*1000;//30分钟DateafterDate=newDate(...
  • 文章转自 : http://www.it610.com/article/271380.htm 亲测可用 . ....import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Dat
  • String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";... //当前时间Date dBefore = new Date();Calendar calendar = Calendar.getInsta...
  • SimpleDateFormat formatter = new SimpleDateFormat( "yyyy.MM.dd HH:mm:ss a ZZZ ");String LgTime = formatter.format(LoginDate1);结果为24小时:星期四 2005.07.14 11:07:812 上午 +0800定...
  • java 当前时间减去7天

    万次阅读 2016-12-30 14:07:23
    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");  Calendar c = new GregorianCalendar();  java.util.Date date = new java.util.Date();  c.setTime(date);  
  • 今天用到缓存,当前时间和当天结束时间距离多少秒? 使用场景:redis缓存,需要设置 键-值 的过期时间.往往我们会使用当前问题。。 使用方法:方案一: 使用Calendar(Java 8之前) public static Integer ...
  • Java当前时间加1

    万次阅读 2011-03-21 08:52:00
    import java.util.Calendar;... * 设置当前时间加1 */ public static void main(String[] args) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); //设置当前日期
  • 把秒数转换为%d:%02d:%02d 格式private String stringForTime(int timeSec) {int totalSeconds = timeSec;int seconds = totalSeconds % 60;int minutes = totalSeconds / 60 % 60;int hours = totalSeconds / 3600;...
  • java 当前时间加减30分钟的时间

    千次阅读 2016-04-13 17:34:00
     System.out.println("当前时间:" + sdf.format(now));   方法一:  long time = 30*60*1000;//30分钟  Date afterDate = new Date(now .getTime() + time);//30分钟后的时间  Date ...
  • Java 当前时间的之前一天,前一个月,前一个星期,前一年,当期时间所在星期,月份,年份表示
  • String time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(System.currentTimeMillis()));... 日期和时间格式由日期和时间模式字符串指定。 在日期和时间模式字符串中,从'A'到'Z'和从'a'到'z...
  • Date currentTime = new Date(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); String dateString = formatter.format(currentTime); return
  • 问题: 众所周知,很多软件会在某一个地方显示当前时间,以方便用户进行操作,今天我贴一段代码实现时间面板的构建和自动更新时间
  • 获取当前日期 //获取当前时间 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 System.out.println(df.format(new Date()));// new Date()为获取当前系统时间 //字符串转 ...
  • java如何获取当前日期和时间

    万次阅读 多人点赞 2019-06-12 18:11:36
    本篇博客主要总结java里面关于获取当前时间的一些方法 System.currentTimeMillis() 获取标准时间可以通过System.currentTimeMillis()方法获取,此方法不受时区影响,得到的结果是时间戳格式的。例如: ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 18,738
精华内容 7,495
关键字:

java当前时间

java 订阅