I have a class DayOfWeek which takes a date from the user and prints the day of the week on that date.
For example the user will enter his date as: (with the format MM DD YYYY)
07 22 2016
and the output should be
FRIDAY
This is my class:
public class DayOfWeek{
public static void main(String[] args){
System.out.println("Enter the date (Format: MM DD YYYY) :");
Scanner sc = new Scanner(System.in);
String month = sc.next();
String day = sc.next();
String year = sc.next();
int m = Integer.parseInt(month);
int d = Integer.parseInt(day);
int y = Integer.parseInt(year);
Calendar cal = Calendar.getInstance();
Date date = new Date(y, m, d);
cal.setTime(date);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println((sdf.format(dayOfWeek)).toUpperCase());
}
}
However when I enter the date stated above (07 22 2016), I don't get the required output (FRIDAY). Instead the output is the current day of week on my system. I am totally stuck on what the problem is.
You're currently passing an int to SimpleDateFormat... you should pass the Date value. You don't need a Calendar at all for that:
// BAD CODE: DON'T USE - KEEP READING
import java.text.*;
import java.util.*;
public class DayOfWeek {
public static void main(String[] args){
System.out.println("Enter the date (Format: MM DD YYYY) :");
Scanner sc = new Scanner(System.in);
String month = sc.next();
String day = sc.next();
String year = sc.next();
int m = Integer.parseInt(month);
int d = Integer.parseInt(day);
int y = Integer.parseInt(year);
// Note the changes here
Date date = new Date(y - 1900, m - 1, d);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
System.out.println(sdf.format(date).toUpperCase());
}
}
I've put the warning there because you're using a deprecated Date constructor - and it's deprecated for good reasons. Basically, java.util.Date is a terrible API and you should avoid using it if you possibly can. Your original call to new Date(y, m, d) was broken because the first parameter to java.util.Date(int, int, int) represents the year with a 1900 base (so a value of 117 means year 2017) and the second parameter represents the month with a 0 base (so a value of 6 means July). Then there's the implicit time zone conversion, which you really don't want.
You'd be much better off using java.time, and in this case the LocalDate class:
import java.time.*;
import java.time.format.*;
import java.util.*;
public class DayOfWeek {
public static void main(String[] args){
System.out.println("Enter the date (Format: MM DD YYYY) :");
Scanner sc = new Scanner(System.in);
String month = sc.next();
String day = sc.next();
String year = sc.next();
int m = Integer.parseInt(month);
int d = Integer.parseInt(day);
int y = Integer.parseInt(year);
LocalDate date = LocalDate.of(y, m, d);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE");
System.out.println(formatter.format(date).toUpperCase());
}
}
Finally, your approach to parsing the user input isn't ideal either - I'd suggest using a DateTimeFormatter for that, too:
import java.time.*;
import java.time.format.*;
public class DayOfWeek {
public static void main(String[] args){
System.out.println("Enter the date (Format: MM DD YYYY) :");
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM dd yyyy");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
LocalDate date = LocalDate.parse(line, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE");
System.out.println(formatter.format(date).toUpperCase());
}
}
Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if you need the output to be Tue rather than 3 (Days of week are indexed starting at (1), instead of going through a calendar, just reformat the string: new SimpleDateFormat("EE").format(date) (EE meaning "day of week, short version").
Note
As pointed by Jon Try and use the latest Date Time Formatter Api for this purpose the Date Api is depricated .
If you have your input as string, rather than Date, you should use SimpleDateFormat to parse it
: new SimpleDateFormat("dd/M/yyyy").parse(dateString)
#JonSkeet's answer is correct and already explains all the problems of the old API and how to use the new one. I'd just like to add another approach with java.time classes.
If you want just to get a String with the day of the week, you can skip the creation of a LocalDate and get directly a java.time.DayOfWeek.
The first part is the same (get the input from the Scanner and create a DateTimeFormatter to parse it).
Then I create a java.time.DayOfWeek from the parsed input, using the from method. So I call getDisplayName, using java.time.format.TextStyle (which is equivalent to EEEE format in #JonSkeet's answer) and a java.util.Locale to make it explicit that I want the day of week's names in English.
// read line from input
Scanner sc = new Scanner(System.in);
// get "07 22 2016" from the scanner
String line = sc.nextLine();
// formatter to parse the input
DateTimeFormatter parser = DateTimeFormatter.ofPattern("MM dd yyyy");
// get the day of the week
DayOfWeek dow = DayOfWeek.from(parser.parse(line));
// get day of week's name
String output = dow.getDisplayName(TextStyle.FULL, Locale.ENGLISH).toUpperCase();
The value of output variable will be FRIDAY - note that I also called toUpperCase(), because the result of getDisplayName is Friday.
The Locale is also important. If you don't specify a locale, it'll use the system's default, and it's not guaranteed to always be English. And it can also be changed without notice, even at runtime, so it's better to make it explicit in your code.
Notes:
The code above will also work if you want to change the language (just use a different Locale). But if you always want an English uppercase name, you can optionally call dow.toString(), which will also return FRIDAY as well.
This code focus only on the day of the week. If you need to use the date for other things than getting FRIDAY (like checking the day, month, etc), then you'll need a LocalDate and #JonSkeet's solution is preferred (and LocalDate has the method getDayOfWeek(), which returns the corresponding DayOfWeek, just in case you need it).
java.time is available only in Java >= 8. If you're using Java <= 7, though, you can use the ThreeTen Backport. The only difference is the package name (org.threeten.bp instead of java.time), but the classes and methods names are the same.
Related
I'm having issues with the below code displays Thursday as the dayOfTheWeek regardless of the date. Any ideas where I've gone wrong with this?
public void CreatePlan() {
editPlanName = findViewById(R.id.editPlanName);
String plan_name = editPlanName.getText().toString();
DatabaseManager db;
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Integer d_name = day;
Integer plan_recipe = 0;
Log.d("Date", String.valueOf(d_name));
String dayOfTheWeek = sdf.format(d_name);
String date = day + "/" + month + "/" +year;
db = new DatabaseManager(getApplicationContext());
Log.d("Recipe name", recipe_name);
db.createPlanRecipe(d_name, date, dayOfTheWeek, recipe_name);
db.createPlan(plan_name, plan_recipe);
}
… Any ideas where I've gone wrong with this?
day in your program is the day of the month from 1 to 31. Therefore d_name holds this number too.
Your SimpleDateFormat accepts formatting a number as a date and time expecting a count of milliseconds since the epoch of January 1, 1970 at 00:00 in UTC. So it will always format a date and time within the first 31 milliseconds after the epoch. Depending on your time zone the point in time that you format falls either on Wednesday, December 31, 1969 or on Thursday, January 1, 1970. So you will either always get Wednesday or always Thursday.
SimpleDateFormat.format(Object) accepts either a Date or a Number. Since Integer is a subclass of Number, it works as described.
The SimpleDateFormat class is notoriously troublesome, you have seen but a small corner of the problems that people often have with it. The Calendar class used in one other answer is poorly designed too. Both are long outdated. I suggest you look into java.time, the modern Java date and time API instead.
Further link: My answer to another question about getting the day of week from an Android date picker.
You are getting the value of the day-of-the-month, the month and the year in the following lines of code but you are not setting these values into the Calendar object which is supposed to give you other information (e.g. the day-of-week) by processing these values:
int day = datepicker.getDayOfMonth();
int month = datepicker.getMonth();
int year = datepicker.getYear();
So, before you try to get any other information from the Calendar object, set these values to the object as shown below:
// Set the picked values into an instance of Calendar
Calendar calendar = Calendar.getInstance();
calendar.clear();// Make sure to call this to reset all fields
calendar.set(year, month - 1, day);// Make sure to decrease month by 1
Now, your rest of code will work as you are expecting e.g. let's say you select 4 as the day-of-the-month, 10 as the month, and 2020 as the year, the following code will give you Sunday as the day-of-the-week.
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
int day = 4;
int month = 10;
int year = 2020;
// Set the picked values into an instance of Calendar
Calendar calendar = Calendar.getInstance();
calendar.clear();// Make sure to call this to reset all fields
calendar.set(year, month - 1, day);// Make sure to decrease month by 1
System.out.println(calendar.getTime());
// Your desired format
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
// The day-of-the-week for the specified date
String dayOfTheWeek = sdf.format(calendar.getTime());
System.out.println(dayOfTheWeek);
}
}
Output:
Sun Oct 04 00:00:00 BST 2020
Sunday
Note that I have decreased the month (picked from the date-picker) by 1 because java.util date-time API is based on 0 as the month of January.
A piece of advice:
I recommend you switch from the outdated and error-prone java.util date-time API and SimpleDateFormat to the modern java.time date-time API and the corresponding formatting API (from the package, java.time.format). Learn more about the modern date-time API from Trail: Date Time.
If your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
By using the modern date-time API:
import java.time.LocalDate;
import java.time.format.TextStyle;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
int dayOfMonth = 4;
int month = 10;
int year = 2020;
// Instantiate a LocalDate object using the picked values
LocalDate date = LocalDate.of(year, month, dayOfMonth);
// The day-of-the-week for the specified date
String dayOfTheWeek = date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println(dayOfTheWeek);
}
}
Output:
Sunday
You have to create Date from your datepicker, then format it to find day like below:
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth();
int year = datePicker.getYear();
Calendar calendar = Calendar.getInstance();
calendar.set(year, month - 1, day);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
dayOfTheWeek = sdf.format(calendar.getTime());
I want to convert two digits year to four digits and also it is possible to come 4 digits
final Integer year = 2020;
final Integer month = 12;
final DateFormat originalFormat = new SimpleDateFormat("MMyy", Locale.US);
final Date monthAndYear = originalFormat.parse(month + String.valueOf(year));
final DateFormat formattedDate = new SimpleDateFormat("yyyy-MM", Locale.US);
System.out.println(formattedDate.format(monthAndYear));
This code fails if the input is 2-2020, which not parsing one digit month.
I want to pass the code by below conditions
year | month || expeected
2020 | 12 || "2020-12"
30 | 2 || "2030-02"
41 | 05 || "2041-05"
You can use YearMonth for this like so:
final DateTimeFormatter YEAR_FORMAT = DateTimeFormatter.ofPattern("[yyyy][yy]");
YearMonth yearMonth = YearMonth.of(
Year.parse(year, YEAR_FORMAT).getValue(),
month);
Note: The year should be a String
Outputs:
2020-12
2030-02
2041-05
I don’t think I’d want to use parsing for this, though it is an option. Your year and month come as numbers, so I find it more natural to handle them as such. Like the others I recommend using YearMonth from java.time, the modern Java date and time API.
final Integer year = 2020;
final Integer month = 12;
YearMonth monthAndYear;
if (0 <= year && year < 100) { // two digits
YearMonth currentMonthAndYear = YearMonth.now(ZoneId.systemDefault());
// Truncate current year to whole centuries
int fullYear = currentMonthAndYear.getYear() / 100 * 100 + year;
monthAndYear = YearMonth.of(fullYear, month);
if (monthAndYear.isBefore(currentMonthAndYear)) { // in the past, wrong
monthAndYear = monthAndYear.plusYears(100);
}
} else {
monthAndYear = YearMonth.of(year, month);
}
System.out.println(monthAndYear);
Output from this example snippet:
2020-12
It’s wordier than the code in the other answers. The upside is that it gives us precise control over which century to use for two digit years. Year 20 and moth 4 give us 2120-04, while year 20 and month 9 give us 2020-09. So both are in the future.
You want the result as a string in the format from your question? We’re lucky, YearMonth.toString() gives us that.
System.out.println(monthAndYear.toString());
The format is ISO 8601.
Link: Wikipedia article: ISO 8601
Use single M for a month in the format. A single M holds good for any allowed number of digits for a month in the modern date-time API. You should stop using the broken and outdated java.util date-time API and switch to the modern date-time API.
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M-[uuuu][uu]");
// Test strings (month-year)
String[] ymStrArr = { "2-2020", "2-20", "02-2020", "02-20" };
for (String ymStr : ymStrArr) {
YearMonth ym = YearMonth.parse(ymStr, formatter);
System.out.println(ym);
}
}
}
Output:
2020-02
2020-02
2020-02
2020-02
String pattern = "";
if(year1.length() == 4){
pattern = "yyyy";
}elif(year1.length() == 2){
pattern = "yy[yy]";
}
YearMonth yearMonth = YearMonth.of(Year.parse(year1, DateTimeFormatter.ofPattern(pattern)).getValue(),month);
System.out.println(yearMonth);
I'm trying to complete the task named Java Date and Time on HackerRank.
Task
You are given a date. You just need to write the method, getDay, which
returns the day on that date.For example, if you are given the date,
August 14th 2017, the method should return MONDAY as the day on that
date.
I tried my best to do the task but I get either the null result or NullPointerException error. I wonder where do I do wrong. Below is my code:
Thanks in advance!
My Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String month = in.next();
String day = in.next();
String year = in.next();
System.out.println(getDay(day, month, year));
}
public static String getDay(String day, String month, String year) {
Calendar cal = Calendar.getInstance();
cal.set(Integer.valueOf(year), (Integer.valueOf(month) - 1), Integer.valueOf(day));
return cal.getDisplayName(cal.get(Calendar.DAY_OF_WEEK), Calendar.LONG, Locale.getDefault());
}
}
Your return is off; you don't want cal.get in the first column of cal.getDisplayName. Currently, I get the month name with your code. Change that to
return cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
And call it like
public static void main(String[] args) {
System.out.println(getDay("14", "8", "2017"));
}
And I get (as expected)
Monday
In new code, I would prefer the new classes in java.time (Java 8+), and a DateTimeFormatter - like,
public static String getDay(String day, String month, String year) {
int y = Integer.parseInt(year), m = Integer.parseInt(month), d = Integer.parseInt(day);
return java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(LocalDate.of(y, m, d));
}
java.time.LocalDate
The modern approach uses the java.time classes.
Import java.time.* to access LocalDate & DayOfWeek classes.
Write getDay method which should be static because it is called in main method.
Retrieve localDate by using of method which takes 3 arguments in "int" format.
convert the getDay method arguments in int format.
finally retrieve name of that day using getDayOfWeek method.
There is one video on this challenge.
Java Date and Time Hackerrank
LocalDate // Represent a date-only value, without time-of-day and without time zone.
.of( 2018 , 1 , 23 ) // Pass year-month-day, 1-12 for January-December.
.getDayOfWeek() // Obtain a `DayOfWeek` enum object.
.getDisplayName( // Automatically localize the name of the day-of-week.
TextStyle.FULL , // How long or abbreviated.
Locale.US // Or Locale.CANADA_FRENCH or so on.
) // Returns `String` such as `Monday` or `lundi`.
For Java 6 & 7, see the ThreeTen-Backport project. For earlier Android, see the ThreeTenABP project.
if you want to use LocalDate, you can use it this way
import java.time.LocalDate;
public static String getDay(int month, int day, int year) {
return LocalDate.of(year, month, day).getDayOfWeek().name();
}
public static String getDay(int month, int day, int year) {
String res= java.time.format.DateTimeFormatter.ofPattern("EEEE")
.format(java.time.LocalDate.of(year, month, day));
return res; }
must use java.time.LocalDate, if u will use direct LocalDate its show compile time error i.e cannot find symbol, so plz use java.time.
You can use new Java8 DateTime API.
public static String getDay(int day, int month, int year)
{
LocalDate dt=LocalDate.of(year, month, day);
System.out.println("day: " + dt.getDayOfWeek().toString());
return dt.getDayOfWeek().toString();
}
A LocalDate is a date without time of day, so fine for our purpose. The of factory method constructs the date that we want. Contrary to the Calendar class used in the question it numbers the months sanely from 1 for January through 12 for December. A LocalDate has a getter for day of week. It returns a constant from the DayOfWeek enum whose toString method gives us a nice readable string such as MONDAY, again in contrast to what we get from Calendar.
public static String findDay(int month, int day, int year) {
Calendar cal = Calendar.getInstance();
cal.set(year, (month - 1), day);
String dayOfWeek = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
return dayOfWeek.toUpperCase();
}
Formatting data and time using java.util date and calendar as follows, where it needed to handle an exception with java.text.SimpleDateFormat in java 7.
public static void main(String[] args){
String inputDateStr = String.format("%s/%s/%s", 23, 04, 1995);
Date inputDate = null;
try {
inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
} catch (ParseException ex) {
Logger.getLogger(JavaApplication28.class.getName()).log(Level.SEVERE, null, ex);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputDate);
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
System.out.println(dayOfWeek);
}
Formatting date and time using java.time classes in java 8 as follows and it is immutable and thread-safe.
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
LocalDateTime dateObj = LocalDateTime.now();
System.out.println("Before formatting: " + dateObj);
DateTimeFormatter formatObj = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");
String formattedDate = dateObj.format(formatObj);
System.out.println("After formatting: " + formattedDate);
}
}
I have been trying to use the date.format(DateTimeFormatter formatter) method to format a list of date strings, where 'date' is a java.time.LocalDate object, for example. The problem is, I cannot find a straight-forward way to create a Year object from a string. For instance, if I have the string yearString = "90". I would like to create a Year object that is equal to this value, and then use the format method to output yearStringNew = "1990". The closest I see to a public constructor is the now() function which returns the current time.
I have also looked into creating a Calendar object and then creating a format-able date object there, but I can only create a Java.util.Date object – as opposed to an object in the Java.time package which could then ideally be formatted by the format function. Am I missing something here?
FYI I'm referencing the Java 8 SDK javadoc https://docs.oracle.com/javase/8/docs/api/
Thank you for your time.
EDIT: Per the request of another user, I have posted my code below; this is the closest I have come to accomplishing what I'm looking for:
//Module 3:
//Format Date Segments
package challenge245E;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
public class TestClass3 {
public static void main(String[] args) throws ParseException {
DateFormatter dateFormatter = new DateFormatter();
String myGroupedSlices [][] =
{
{"1990", "12", "06"},
{"12","6", "90"}
};
dateFormatter.formatDates(myGroupedSlices);
}
}
class DateFormatter {
public Date[][] formatDates(String[][] groupedDates) throws ParseException {
Date[][] formattedDates = new Date[groupedDates.length][3];
DateFormat yearFormat = new SimpleDateFormat("YYYY");
DateFormat monthFormat = new SimpleDateFormat("MM");
DateFormat dayFormat = new SimpleDateFormat("dd");
//iterate through each groupedSlices array
for (int i=0; i<groupedDates.length;i++) {
//Conditions
if (groupedDates[i][0].length()<3) {
//MDDYY format: if date[0].length < 3
//Re-arrange into YDM order
String m = groupedDates[i][0];
String y = groupedDates[i][2];
groupedDates[i][0] = y;
groupedDates[i][2] = m;
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("MDY Order: " + Arrays.toString(formattedDates[i]));
}
if (groupedDates[i][0].length()>3) {
//YYYYMMDD format: if date[0].length > 3
//convert dates to correct format
formattedDates[i][0] = yearFormat.parse(groupedDates[i][0]);
formattedDates[i][1] = monthFormat.parse(groupedDates[i][1]);
formattedDates[i][2] = dayFormat.parse(groupedDates[i][2]);
//testing if block
System.out.println("YMD Order: " + Arrays.toString(formattedDates[i]));
}
}
return formattedDates;
}
}
If I understand your requirement correctly, have a look at the LocalDate.parse() methods.
Example:
LocalDate date = LocalDate.parse("1990-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
int year = date.getYear(); // 1990
Parse Each Number Separately
It’s good to see you using the java.time framework rather than the troublesome old date-time classes. The old java.util.Date/.Calendar classes have been supplanted by the new framework.
The DateTimeFormatter class parses any two digit year as being in the 2000s. From class doc:
If the count of letters is two… will parse using the base value of 2000, resulting in a year within the range 2000 to 2099 inclusive.
To override this behavior, see this Answer by assylias. But that issue may be moot in your case. You already have the individual year, month, and date values isolated. So they need not be parsed together.
I suggest you convert each string into a integer. For the year, if less than 100 then add 1900.
String inputYear = "90";
String inputMonth = "12";
String inputDayOfMonth = "6";
int year = Integer.parseInt( inputYear );
int month = Integer.parseInt( inputMonth );
int dayOfMonth = Integer.parseInt( inputDayOfMonth );
if( year < 100 ) { // If two-digit year, assume the 1900s century. Even better: Never generate two-digit year text!
year = ( year + 1900 );
}
LocalDate localDate = LocalDate.of( year , month , dayOfMonth );
Create an Instance of class GregorianCalendar, set your date in that calendar and then use the method toZonedDateTime(). This will give you ZonedDateTime instance. form it you can use method LocalDate.from(TemporalAccessor temporal) method to get your LocalDate. Here how it might look:
//....
GregorianCalendar calendar = new GregorianCalendar();
// Set the deasired date in your calendar
LocalDate localDate = LocalDate.from(calendar.toZonedDateTime());
//...
import java.time.LocalDate;
public class DaysTilNextMonth {
public static void main(String[] args) {
//create an object for LocalDate class
LocalDate date = LocalDate.now();
//get today's day
int today = date.getDayOfMonth();
//get number of days in the current month
int numOfDaysInMonth = date.lengthOfMonth();
//compute the days left for next month
int dayForNextMonth = numOfDaysInMonth - today;
//display the result
System.out.println("The next month is: " + date.plusMonths(7).getMonth());
System.out.println("We have " + dayForNextMonth + " days left until first day of next month.");
}
}
Is there any simple way to use Scanner and place it into a variable of type GregorianCalendar or to convert the string into a GregorianCalendar?
Specifically, I need the user to enter a date in the format mm/dd/yyyy on one line, and a starting and ending time on another (user doesn't have to enter an ending time if the event has none) in the form of a 24 hour clock (eg. 15:30 = 3:30pm).
Anyone have any ideas? All I see online is how to print a GregorianCalendar in different string formats.
Use SimpleDateFormat. This class is mean to convert String into java.util.Date and vice versa.
Here's a brief example:
//initialize the Scanner
Scanner scanner = new Scanner(System.in);
//read the desired input
String dateAsString = scanner.next();
//create an instance of SimpleDateFormat
//MM: month (2 digits)
//dd: day (2 digits)
//yyyy: year (four digits)
//more of this in the javadoc
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//parse the String as a Date
Date desiredDate = sdf.parse(dateAsString);
//Calendar.getInstance() should return a GregorianCalendar instance by "default"
Calendar calendar = Calendar.getInstance();
//setting the date into the Calendar
calendar.setTime(desiredDate);