Showing posts with label Calendar. Show all posts
Showing posts with label Calendar. Show all posts

Tuesday, 16 April 2013

Converting a Date object to a calendar object

Leave a Comment
Calendar cal = Calendar.getInstance();
   cal.setTime(date);
   cal.set(Calendar.HOUR_OF_DAY, 0);
   cal.set(Calendar.MINUTE, 0);    
   cal.set(Calendar.SECOND, 0);    
   cal.set(Calendar.MILLISECOND, 0);    
          
   return cal.getTime();

Read More...

Compare Two Date In Java

Leave a Comment
public static void main( String[] args ) 
    {
     try{
 
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Date date1 = sdf.parse("2009-12-31");
         Date date2 = sdf.parse("2010-01-31");
 
         System.out.println(sdf.format(date1));
         System.out.println(sdf.format(date2));
 
         if(date1.compareTo(date2)>0){
          System.out.println("Date1 is after Date2");
         }else if(date1.compareTo(date2)<0){
          System.out.println("Date1 is before Date2");
         }else if(date1.compareTo(date2)==0){
          System.out.println("Date1 is equal to Date2");
         }else{
          System.out.println("How to get here?");
         }
 
     }catch(ParseException ex){
      ex.printStackTrace();
     }
    }

Read More...

String to Date Conversion in Java

Leave a Comment
//String to Date Conversion
 stringDate = "10-04-2013";

 public Date stringToDate(String stringDate)
 {
  Date date = null;
  try {
   SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
   date = sdf.parse(stringDate);
   System.out.println(date);
   return date;
  } catch (ParseException e) {
   e.printStackTrace();
   return date;
  }
 }

Read More...

Timestamp to Date Conversion In Java

Leave a Comment
Use This Import.
import java.sql.Timestamp;
//Timestamp to Date Conversion
 public Date timeStampToDate(Timestamp timestamp)
 {
  Date date = null;
  try
  {
    date = new Date(timestamp.getTime());
    return date;
  }catch (Exception e) {
   e.printStackTrace();
   return date;
  }
 }

Read More...

Wednesday, 10 April 2013

Convert Secons in to mm:ss formatted time

Leave a Comment
/**
  * Converting Second In to MM:SS time
  * @param seconds
  * @author harit Kumar
  * @return time MM:SS
  */
 public String secToTime(int seconds)
 {
  String time= "";
  if(seconds > 59)
  {
   int minutes = seconds/60;
   int sec = seconds%60;
   time = minutes+":"+sec;
  }
  else 
  {
   time = "00:"+seconds;
  }
  return time;
 }

Read More...

Sunday, 7 April 2013

Increment & Decrements Date In Java

Leave a Comment
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date;
/**
 *  @author Harit 
 *  */ 

public class IncrementDecrementDate 
{ 
 public static void main(String args[]) 
 { 
  //Using Calendar to increment and decrement days from date in Java 
  Date today = new Date(); 
  System.out.println("Today is " + toddMMyy(today)); 
  Calendar cal = Calendar.getInstance(); 
  
  //adding one day to current date 
  cal.add(Calendar.DAY_OF_MONTH, 1); 
  Date tommrrow = cal.getTime(); 
  System.out.println("Tomorrow will be " + toddMMyy(tommrrow));
  
  //substracting two day from date in Java 
  cal.add(Calendar.DAY_OF_MONTH, -2); 
  Date yesterday = cal.getTime(); 
  System.out.println("Yesterday was " + toddMMyy(cal.getTime())); 
  
  
 } 
 
 public static String toddMMyy(Date day)
 { 
  SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy"); 
  String date = formatter.format(day);
  return date; 
 } 
 
 }




Read More...

Monday, 25 February 2013

Between 11:20 to 12:00 of specified date Java

Leave a Comment

Calendar cal = Calendar.getInstance();
cal.setTime(date);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minutes = cal.get(Calendar.MINUTE);
if (hour == 11 && minutes >= 20 || hour == 12 && minutes <= 0) 
{
  //Your Logic
}
Read More...

Get Next Date In Java

Leave a Comment

public class NextDate
{ public static void main(String[] args)
{
  int oneDay = 1000 * 60 * 60 * 24;
  Date date = new Date();
  SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
  String currDate = dateFormat.format(date.getTime());
  String nextDate = dateFormat.format(date.getTime() + oneDay);
  System.out.println("Currnent date: " + currDate);
  System.out.println("Next date: " + nextDate);
}
}
Read More...

Thursday, 7 February 2013

Find total hours between two Dates

Leave a Comment

long secs = (this.endDate.getTime() - this.startDate.getTime()) / 1000;
int hours = secs / 3600;    
secs = secs % 3600;
int mins = secs / 60;
secs = secs % 60;
Read More...

Monday, 4 February 2013

convert a string of time to 24 hour format

Leave a Comment
public class App {
  public static void main(String[] args) {
    try {
        System.out.println(convertTo24HoursFormat("12:00AM")); // 00:00
        System.out.println(convertTo24HoursFormat("12:00PM")); // 12:00
        System.out.println(convertTo24HoursFormat("11:59PM")); // 23:59
        System.out.println(convertTo24HoursFormat("9:30PM"));  // 21:30
    } catch (ParseException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  // Replace with KK:mma if you want 0-11 interval
  private static final DateFormat TWELVE_TF = new SimpleDateFormat("hh:mma");
  // Replace with kk:mm if you want 1-24 interval
  private static final DateFormat TWENTY_FOUR_TF = new SimpleDateFormat("HH:mm");

  public static String convertTo24HoursFormat(String twelveHourTime)
        throws ParseException {
    return TWENTY_FOUR_TF.format(
            TWELVE_TF.parse(twelveHourTime));
  }
}
Read More...

Thursday, 31 January 2013

How to get Month Name

Leave a Comment
Java Calendar returns month in numeric integer format. To get month name in string (Jan, Feb, Mar, …), we have to use SimpleDateFormat class. First calendar date should convert into millisecond to parse into date object. SimpleDateFormat returns this date in month name string.

import java.util.Calendar;
import java.text.SimpleDateFormat;

public class MonthName {

    public static void main(String[] args) {
        Calendar ca1 = Calendar.getInstance();

        // set(year, month, date) month 0-11
        ca1.set(2009, 05, 25);

        // int iMonth=ca1.get(Calendar.MONTH);

        java.util.Date d = new java.util.Date(ca1.getTimeInMillis());

        System.out.println("Month Name :"+new SimpleDateFormat("MMMM").format(d));
        System.out.println("Month Name :"+new SimpleDateFormat("MMM").format(d));
    }
}
 
Output
Month Name in String:June

Month Name in String :Jun
Read More...

Get Month Name

Leave a Comment

In this Example we want to describe you a code that help you in understanding a how to get a 'Get Month Name Example'.For this we have a class name 'GetMonthNameExample'. Inside the main method we declared a String array name month name. This String array variable is initialized with month name values.

1)getInstance ( )  -  This method return you the calendar object with a specific time zone and locale.

2)get(Calendar.Month) - This get  method return you the current month
Finally the System.out.print print the Month name  from String variable month.

GetMonthNameExample.java

import java.util.*;

public class GetMonthNameExample {

  public static void main(String args[]) {

  String[] monthName = {"January""February",
  "March""April""May""June""July",
  "August""September""October""November",
  "December"
  };

  Calendar cal = Calendar.getInstance();
  String month = monthName[cal.get(Calendar.MONTH)];
  System.out.println("Month name: " + month);
  }
}

Output:

Month name: October
Read More...

Sunday, 27 January 2013

Get Last Day of The Month

Leave a Comment

Calendar class inherits from Java.util.calendar.Calendar is  base abstract class, that is used for converting between a Date object and a set of integer fields such asYEARMONTHDAYHOUR.. A Date object  specific instant in time with millisecond.

In this Tutorial we want to describe you a code that helps you in getting the last day of the month. For this we have a class name MonthDaysExample.Inside the main method the calendar call the get Instance method  ( ) returns you the calendar object with a specific time zone and locale. we declared and  initialized a int variable year, month and date.

1)calendar.set( )  -This method set the field for year, month and date.
2)getActualMaximum( )- This method  Return the maximum value for this field, given the current date and store its value int variable max day.

The println print the Max Day  from the int variable max day of max day of month February 2009.

In the same way we print the Max day of  February 2004 in this code.
MonthDaysExample.java

import java.text.*;
import java.util.*;

public class MonthDaysExample {

  public static void main(String args[]) {

  Calendar calendar = Calendar.getInstance();

  int year = 2009;
  int month = Calendar.FEBRUARY;
  int date = 1;

  calendar.set(year, month, date);

  int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  System.out.println("Max Day: " + maxDay);

  calendar.set(2004, Calendar.FEBRUARY, 1);
  maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
  System.out.println("Max Day: " + maxDay);

  }
}

Output:

Max Day: 28

Max Day: 29
Read More...

Wednesday, 23 January 2013

Add AM PM to time using SimpleDateFormat

Leave a Comment

package Time;
import java.text.SimpleDateFormat;
import java.util.Date;

public class AddAMPMToFormattedDate {

  public static void main(String[] args) {

    //create Date object
    Date date = new Date();
   
     //formatting time to have AM/PM text using 'a' format
     String strDateFormat = "yyyy-MM-dd HH:mm:ss a";
     SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
     
     System.out.println("Time with AM/PM field : " + sdf.format(date));

  }
}

Output:
Time with AM/PM field : 24:01:2013 10:33:50 AM

Read More...

(UTC/GMT) Coordinated Universal Time

Leave a Comment
See GMT Time Here: http://www.worldtimeserver.com/current_time_in_UTC.aspx

Coordinated Universal Time (UTC) is the primary time standard by which the world regulates clocks and time. It is one of several closely related successors to Greenwich Mean Time (GMT). For most purposes, UTC is synonymous with GMT, but GMT is no longer precisely defined by the scientific community.


Time zones around the world are expressed as positive or negative offsets from UTC, as in the list of time zones by UTC offset.
UTC is the time standard used for many internet and World Wide Web standards. The Network Time Protocol, designed to synchronise the clocks of computers over the Internet, encodes times using the UTC system.[4]
Computer servers, online services and other entities that rely on having a universally accepted time use UTC as it is more specific than GMT. If only limited precision is needed, clients can obtain the current UTC time from a number of official Internet UTC servers. For sub-microsecond precision, clients can obtain the time from satellite signals.
UTC is also the time standard used in aviation[5], e.g., for flight plans and air traffic control clearances. Weather forecasts and maps all use UTC to avoid confusion about time zones and daylight saving time.
Read More...

Thursday, 17 January 2013

SimpleDateFormat JAVA

Leave a Comment
java.lang.Object
  extended byjava.text.Format
      extended byjava.text.DateFormat
          extended byjava.text.SimpleDateFormat
 
public class SimpleDateFormat extends DateFormat
SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. It allows for formatting (date -> text), parsing (text -> date), and normalization.
 
It allows you to define your own formatting patterns that are used to display date and time information. One of its constructors is shown here:
SimpleDateFormat(String formatString)

The argument formatString describes how date and time information is displayed. An example of its use is given here:

SimpleDateFormat sdf = SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");

In most cases, the number of times a symbol is repeated determines how that data is presented. Text information is displayed in an abbreviated form if the pattern letter is repeated less than four times. Otherwise, the unabbreviated form is used. For example, a zzzz pattern can display Pacific Daylight Time, and a zzz pattern can display PDT. For numbers, the number of times a pattern letter is repeated determines how many digits are presented. For example, hh:mm:ss can present 01:51:15, but h:m:s displays the same time value as 1:51:15.

Finally, M or MM causes the month to be displayed as one or two digits. However, three or more repetitions of M cause the month to be displayed as a text string.
The following program shows how this class is used:
// Demonstrate SimpleDateFormat.
import java.text.*;
import java.util.*;
public class SimpleDateFormatDemo {
public static void main(String args[]) {
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("E MMM dd yyyy");
System.out.println(sdf.format(date));
}
}

Sample output from this program is shown here:
11:51:50
19 Feb 1999 11:51:50 CST
Fri Feb 19 1999

 
Read More...

Thursday, 3 January 2013

how to get a list of dates between two dates in java

Leave a Comment

List<Date> dates = new ArrayList<Date>();
long interval = 1000 * 60 * 60*24; //1 hour in millis
long endTime = lastDateOfPreviousMonth.getTime();
long curTime = firstDateOfPreviousMonth.getTime();
while (curTime <= endTime) 
{
 dates.add(new Date(curTime));
 curTime += interval;
}
Read More...

Get first and last date of the previous month in java

Leave a Comment

Calendar aCalendar = Calendar.getInstance();
aCalendar.set(Calendar.DATE, 1);
aCalendar.add(Calendar.DAY_OF_MONTH, -1);
Date lastDateOfPreviousMonth = aCalendar.getTime();
aCalendar.set(Calendar.DATE, 1);
Date firstDateOfPreviousMonth = aCalendar.getTime();
Read More...

Tuesday, 20 November 2012

Add or substract hours to current time using Java Calendar

Leave a Comment

  1. /*
  2.   Add or substract hours to current time using Java Calendar
  3.   This example shows how to add or substract hours in current time  
  4.   using Java Calendar class.
  5. */
  6.  
  7. import java.util.Calendar;
  8.  
  9. public class AddHoursToCurrentDate {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create Calendar instance
  14.     Calendar now = Calendar.getInstance();
  15.  
  16.     System.out.println("Current Date : " + (now.get(Calendar.MONTH) + 1)
  17.                         + "-"
  18.                         + now.get(Calendar.DATE)
  19.                         + "-"
  20.                         + now.get(Calendar.YEAR));
  21.    
  22.     System.out.println("Current time : " + now.get(Calendar.HOUR_OF_DAY)
  23.                       + ":"
  24.                       + now.get(Calendar.MINUTE)
  25.                       + ":"
  26.                       + now.get(Calendar.SECOND));
  27.                      
  28.     //add hours to current date using Calendar.add method
  29.     now.add(Calendar.HOUR,10);
  30.  
  31.     System.out.println("New time after adding 10 hours : "
  32.                       + now.get(Calendar.HOUR_OF_DAY)
  33.                       + ":"
  34.                       + now.get(Calendar.MINUTE)
  35.                       + ":"
  36.                       + now.get(Calendar.SECOND));
  37.  
  38.     /*
  39.      * Java Calendar class automatically adjust the date accordingly if adding
  40.      * hours to the current time causes current date to be changed.
  41.      */
  42.      
  43.     System.out.println("New date after adding 10 hours : "
  44.                         + (now.get(Calendar.MONTH) + 1)
  45.                         + "-"
  46.                         + now.get(Calendar.DATE)
  47.                         + "-"
  48.                         + now.get(Calendar.YEAR));
  49.    
  50.     //substract hours from current date using Calendar.add method
  51.     now = Calendar.getInstance();
  52.     now.add(Calendar.HOUR-3);
  53.  
  54.     System.out.println("Time before 3 hours : " + now.get(Calendar.HOUR_OF_DAY)
  55.                       + ":"
  56.                       + now.get(Calendar.MINUTE)
  57.                       + ":"
  58.                       + now.get(Calendar.SECOND));
  59.    
  60.   }
  61. }
  62.  
  63. /*
  64. Typical output would be
  65. Current Date : 12-25-2007
  66. Current time : 18:31:42
  67. New time after adding 10 hours : 4:31:42
  68. New date after adding 10 hours : 12-26-2007
  69. Time before 3 hours : 15:31:42
  70. */
Read More...

Add or substract days to current date using Java Calendar

Leave a Comment

  1. /*
  2.   Add or substract days to current date using Java Calendar
  3.   This example shows how to add or substract days in current date and time values
  4.   using Java Calendar class.
  5. */
  6.  
  7. import java.util.Calendar;
  8.  
  9. public class AddDaysToCurrentDate {
  10.  
  11.   public static void main(String[] args) {
  12.    
  13.     //create Calendar instance
  14.     Calendar now = Calendar.getInstance();
  15.    
  16.     System.out.println("Current date : " + (now.get(Calendar.MONTH) + 1)
  17.                         + "-"
  18.                         + now.get(Calendar.DATE)
  19.                         + "-"
  20.                         + now.get(Calendar.YEAR));
  21.    
  22.     //add days to current date using Calendar.add method
  23.     now.add(Calendar.DATE,1);
  24.  
  25.     System.out.println("date after one day : " + (now.get(Calendar.MONTH) + 1)
  26.                         + "-"
  27.                         + now.get(Calendar.DATE)
  28.                         + "-"
  29.                         + now.get(Calendar.YEAR));
  30.  
  31.    
  32.     //substract days from current date using Calendar.add method
  33.     now = Calendar.getInstance();
  34.     now.add(Calendar.DATE-10);
  35.  
  36.     System.out.println("date before 10 days : " + (now.get(Calendar.MONTH) + 1)
  37.                         + "-"
  38.                         + now.get(Calendar.DATE)
  39.                         + "-"
  40.                         + now.get(Calendar.YEAR));
  41.    
  42.   }
  43. }
  44.  
  45. /*
  46. Typical output would be
  47. Current date : 12-25-2007
  48. date after one day : 12-26-2007
  49. date before 10 days : 12-15-2007
  50. */
Read More...