Java Program to Store the Time in a Single Integer Variable

You are currently viewing Java Program to Store the Time in a Single Integer Variable

Java program to store the time in a single integer variable

// Java program to store the date in a 
// single integer variable

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int dd, mm, yy;
    int date;

    System.out.printf("Enter date (dd mm yyyy) format: ");
    dd = SC.nextInt();
    mm = SC.nextInt();
    yy = SC.nextInt();

    System.out.printf("\nEntered date is: %02d/%02d/%04d\n", dd, mm, yy);

    date = 0;

    //dd storing in byte 0
    date |= (dd & 0xff);

    //mm storing in byte 1
    date |= (mm & 0xff) << 8;

    //yy storing in byte 2 and 3
    date |= (yy & 0xffff) << 16;

    System.out.printf("Date in single variable: %d [Hex: %08X] \n", date, date);

    //Now extract date from an integer variable

    //dd from byte 0
    dd = (date & 0xff);

    //mm from byte 1
    mm = ((date >> 8) & 0xff);

    //yy from byte 2 and 3
    yy = ((date >> 16) & 0xffff);

    System.out.printf("Date after extracting: %02d/%02d/%04d\n", dd, mm, yy);
  }
}

Output

Enter time (hh mm ss) format: 10 11 12

Entered time is: 10:11:12
Time in single variable: 789258 [Hex: 000C0B0A] 
Time after extracting: 10:11:12

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply