The common methods of calendar time operation in Java _java

Source: Internet
Author: User
Tags current time dateformat mongodb

The examples in this article share the common methods for calendar time operations, as follows

Package test;
Import Java.text.SimpleDateFormat;
Import Java.util.Calendar;


Import Java.util.Date;


/** * Date and Calendar common methods, date many methods have been deprecated, so the calendar mainly * * * @author tuzongxun123 */public class Dateandcalendartest {


public static void Main (string[] args) {//Gets the current system time directly with Date, as a result: Tue may 08:25:44 CST 2016 date = new Date ();
Many of the methods in date, such as getting a year, a month, a day, etc., and the setting of a year, a month, a day, etc. are no longer recommended,//suggest the use of calendar methods of substitution, so do not make records//get the number of milliseconds of the specified date, commonly used to compare the size of two dates.


Date.gettime ();


Use calendar to get the current system time, need to get the Calendar object to convert to date output Calendar calendar = Calendar.getinstance ();


This method is equivalent to the gettime in date, obtaining the millisecond number of the current time Calendar.gettimeinmillis ();


Gets the date of the first day of the week on which the specified date is, and the first day of the week by default is Sunday Calendar.getfirstdayofweek ();


Returns the year in which the current calendar date is located, such as 2016 calendar.get (1);
Calendar turns to date, output results: Tue may 09:31:59 CST 2016 Date date2 = Calendar.gettime ();


System.out.println (DATE2);
Calendar set year, month, day, output results: Mon June 09:31:59 CST 2013//Related common overload methods: Calendar.set (years, month, date, hourofday, minute); Calendar.set (year, month, date, Hourofday, minute, second); the parameters are int calendar.set (2013, 5, 3);


System.out.println (Calendar.gettime ());
Use calendar to set year, output results: Fri June 09:42:43 CST Calendar.set (Calendar.year, 2011);


System.out.println (Calendar.gettime ());
Use calendar and number settings month, note Month starting from 0, representing January, output results: Mon 09:45:32 CST calendar.set (calendar.month, 0);


System.out.println (Calendar.gettime ());
Set months with calendar and self constants, note the month starting from 0, representing January, output results: Thu Feb 09:47:07 CST calendar.set (Calendar.month, calendar.february);


System.out.println (Calendar.gettime ());
Use calendar and number setting days, output results: Sat Feb 09:48:25 CST//Calendar.set (Calendar.day_of_month, 5) The result is the same;
Calendar.set (Calendar.date, 5);


System.out.println (Calendar.gettime ());
Set hours Calendar.set (Calendar.hour, 15);


System.out.println (Calendar.gettime ());


Set Calendar Time Calendar.settimeinmillis (0) based on the number of milliseconds;
Date turns string, output result: 2016-05-03 09:25:29 string fordate = datetostring (New Date ());


System.out.println (fordate); String to date, output result: Thu Nov 12 13: 23:11 CST 2015 Date strdate = stringtodate ("2015-11-12 13:23:11");


System.out.println (strdate);
Date to Calendar, output results: 2015 calendar calendar2 = Datetocalendar (strdate);


System.out.println (Calendar2.get (1)); /** * Converts the specified date type time to the specified format string * * @author: Tuzongxun * @Title: datetostring * @param @param date * @return void * @dat
E May 3, 2016 9:09:25 AM * @throws */static string datetostring (date date) {String str = "Yyyy-mm-dd hh:mm:ss";
SimpleDateFormat format = new SimpleDateFormat (str);
String DateFormat = Format.format (date);
return dateformat; /** * Converts a string in the specified date format to the date type * * @author: Tuzongxun * @Title: Stringtodate * @param @param string * @return void * @dat
E May 3, 2016 9:16:38 AM * @throws */static Date Stringtodate (String string) {string str = "Yyyy-mm-dd hh:mm:ss";
SimpleDateFormat format = new SimpleDateFormat (str);
Date date = new Date ();
try {date = Format.parse (string);} catch (Exception e) {e.getstacktrace ();} return date; /** * Converts the specified date type dates to CalendAR type * * @author: Tuzongxun * @Title: Datetocalendar * @param @param date * @return void * @date May 3, 2016 9:13:49 AM * @throws */Static calendar Datetocalendar (date date) {Calendar calendar = calendar.getinstance (); Calendar.settime (date)
;
return calendar;
 }
}

What kind of pits are there?

Where is the pit:

One of the things that I've contacted before involves moving some data to another collection in the MongoDB database 00:00:00 every day--a table in a relational database. This collection name is a fixed name plus the year and month in which the current two month ago dates.

This feature was there before I touched the project, which was implemented by my colleagues and wrote a Java timed task.

The colleague is not in our company now, but recently found that the function has some problems, the data movement is not as expected, the original should exist February data is in the January table.

The root of the pit:

MongoDB related issues for the time being I maintain, this problem also naturally need me to solve, so he turned over his code to read it again. It turns out that the problem is in the way the calendar is related.

To transfer data two months ago, first get the date two months ago, and the code for his table name is this:

Private String Getdatacollectionname () { 
    Calendar calendar = calendar.getinstance (); 
    try { 
      calendar.set (calendar.date,-day); 
      Return "Alarm_" + toolutils.datetoformatstrdate (Calendar.gettime (), "yyyy_mm"); 
    } catch (Exception e) { 
    logger.error ("{}: Data transformating failed,{}", This.getclass (). GetName (), E.getmessage ()) ; 
    } 
    return null; 
 } 

The problem is in the set method of the Calendar, including the start and end times of subsequent query data, as well as Calendar.set (Calendar.date,-day);

This method at first seems to be setting the date to subtract the specified number of days from the current date, but in fact the result is not expected to get the date two months ago (the day it defines is 60, which is two months).

Landfills

After I found out why, I replaced the method with the set to add, as the parameters in it did not move, and the result proved that the method was really able to implement the current function, and the result was the desired result.

Of course, you can also change the parameters without changing the method, such as Calendar.set (Calendar.date, Calendar.get (Calendar). DATE)-day);

The above is the entire content of this article, I hope to master the calendar time to operate the common methods to help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.