I'm trying to write a Calendar in java that outputs an html web page with a Calendar inside of a table, but I've run into a problem when trying to get the number of days in a specific month during a specific year.
This is the bit of code I'm using:
//accept input from command prompt in form of MONTH, DAY, YEAR
String date = args[0];
SimpleDateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
Date convertedDate = new Date();
try
{
convertedDate = df.parse(date);
}
catch(Exception e)
{
System.out.print(e);
}
Calendar cal = Calendar.getInstance();
cal.setTime(convertedDate);
year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
//get number of days in month
int numDays, startMonth;
numDays = cal.getActualMaximum(DAY_OF_MONTH);
and I'm getting an error from that last line that reads:
error: cannot find symbol and it points to the DAY_OF_MONTH variable.
How can I resolve this?
Use Calendar.DAY_OF_MONTH:
numDays = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
It's a static field on the Calendar class.
Related
I have a method that collect the year, month and day from a DatePicker and stores them in separate integers.
public void onDateChanged(DatePicker datePicker, int year, int month, int dayOfMonth) {
yearD = year;
monthD = (month + 1);
dayD = dayOfMonth;
}
How can I transform these integers to a SimpleDateFormat with the pattern "yyyy-MM-dd"?
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
First you create a calendar object such as
Calendar c = Calendar.getInstance();
c.set(year, month - 1, day, 0, 0);
Now format as per your requirement as below
Date date = c.getTime();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date);
Though I have not tested the code on IDE but I hope it will give you the solution.
I guess that should do the trick:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = new Calendar().set(year, month, day);
formatter.format(cal);
Even though this is not strictly an answer, I would recommend you to jump from the old and error prune Calendar / DatePicker classes, to the intuitive new LocalDate class. If you are interested, let me know and I'll tell you how :)
Here is my code that convert string ("12/05/2015") from textView into date with the same format, and i want to get from that date its day of week.
String d1=((TextView)findViewById(R.id.tvDate2)).getText().toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date convertedDate = new Date();
try {
convertedDate = dateFormat.parse(d1);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar c = Calendar.getInstance();
c.setTime(convertedDate);
int day= c.get(Calendar.DAY_OF_WEEK);
System.out.println("day:"+day);
when i try 22/05/2015 (friday) it returns 4
but for 29/05/2015 (also friday) it returns 6
so where is the problem
You've mixed up the month and the day.
Either change your format to "dd/MM/yyyy" or change the inputted date string to "05/22/2015".
You have got your months and days flipped around in your format string. Try:
"dd/MM/yyyy"
I am using the below code
#SuppressWarnings("deprecation")
Date d = new Date (2014,01,9);
System.out.println(d);
DateFormat df = new SimpleDateFormat("yyyyMMdd");
final String text = df.format(d);
System.out.println(text);
I am getting below output.
3914-02-09
39140209
Does any one know why there is 3914?
Thanks,
Mahesh
The javadoc for the constructor you're using java.sql.Date(int,int,int) reads (in part),
year - the year minus 1900; must be 0 to 8099. (Note that 8099 is 9999 minus 1900.)
so you should use (assuming you mean this year)
Date d = new Date (2015-1900,01,9);
From Java Docs,
Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date) or GregorianCalendar(year + 1900, month, date).
Allocates a Date object and initializes it so that it represents midnight, local time, at the beginning of the day specified by the year, month, and date arguments.
Parameters:
year the year minus 1900.
month the month between 0-11.
date the day of the month between 1-31.
Code
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
int year = 2014;
int month = 01;
int day = 9;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month - 1);
cal.set(Calendar.DAY_OF_MONTH, day);
java.sql.Date date = new java.sql.Date(cal.getTimeInMillis());
System.out.println(sdf.format(date));
}
output
2014-01-09
How do I create a function which take current date and return month name?
I have only date its not current date it can be any date like 2013/4/12 or 23/8/8.
Like String monthName("2013/9/11");
when call this function return the month name.
This should be fine.
It depends on the format of date.
If you try with February 1, 2011
it would work, just change this string "MMMM d, yyyy" according to your needs.
Check this for all format patterns.
And also, months are 0 based, so if you want January to be 1, just return month + 1
private static int getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int month = cal.get(Calendar.MONTH);
return month + 1;
}
If you want month name try this
private static String getMonth(String date) throws ParseException{
Date d = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
String monthName = new SimpleDateFormat("MMMM").format(cal.getTime());
return monthName;
}
As I said, check web page I posted for all format patterns. If you want only 3 characters of month, use "MMM" instead of "MMMM"
java.time
I am contributing the modern answer.
System.out.println(LocalDate.of(2013, Month.SEPTEMBER, 11) // Define the date
.getMonth() // Get the month
.getDisplayName( // Get the month name
TextStyle.FULL_STANDALONE, // No abbreviation
Locale.ENGLISH)); // In which language?
Output is:
September
Use LocalDate from java.time, the modern Java date and time API, for a date.
Use LocalDate.getMonth() and Month.getDisplayName() to get the month name.
Avoid Date, Calendar and SimpleDateFormat used in the old answers from 2013. Those classes are poorly designed, troublesome and long outdated. The modern API is so much nicer to work with. Also avoid switch/case for this purpose since the month names are already built in, and using the library methods gives you clearer, terser and less error-prone code.
Use LocalDate
LocalDate today = LocalDate.now(ZoneId.systemDefault());
LocalDate aDate = LocalDate.of(2013, Month.SEPTEMBER, 11); // 2013/9/11
LocalDate anotherDate = LocalDate.of(2023, 8, 8); // 23/8/8
If you are getting the date as string input, parse the string using a DateTimeFormatter:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("u/M/d");
String stringInput = "2013/4/12";
LocalDate date = LocalDate.parse(stringInput, dateFormatter);
System.out.println(date);
2013-04-12
Use LocalDate.getMonth() and Month.getDisplayName()
To get the month name you first need to decide in which language you want the month name. I am taking English as an example and still using date from the previous snippet:
String monthName = date.getMonth()
.getDisplayName(TextStyle.FULL_STANDALONE, Locale.ENGLISH);
System.out.println(monthName);
April
Java knows the month names in a wealth of languages. If you want the month name in the user’s language, pass Locale.getDefault() as the second argument to getDisplayName().
Link
Oracle tutorial: Date Time explaining how to use java.time.
Use this code -
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
int month = calendar.get(Calendar.MONTH);
So now you have month number, you can use switch case to get name for that month.
If your date is in string format use this-
Date date = new SimpleDateFormat("yyyy-MM-dd").format(d)
Simple solution to get current month by name:
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
String currentMonth = formatterMonth.format(new Date(System.currentTimeMillis()));
Function to get any month by name using format 2013/9/11: (not tested)
private String monthName(String dateToCheck){
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
date = formatter.parse(dateToCheck);
SimpleDateFormat formatterMonth = new SimpleDateFormat("MMMM");
return formatterMonth.format(new Date(date.getTime()));
}
I am using a function like this:
public String getDate(String startDate) throws ParseException {
#SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = null;
try {
d = sdf.parse(startDate);
sdf.applyPattern("MMMM dd, YYYY"); //this gives output as=> "Month date, year"
} catch (Exception e) {
Log.d("Exception", e.getLocalizedMessage());
}
return sdf.format(d);
}
You can obtain the "number" of the month as described in the other answer and then you could simply use a switch to obtain a name.
Example:
switch(month) {
case 0:
your name is January
break;
...
}
P.S. I think months are zero-based but I'm not 100% sure...
//get current date
SimpleDateFormat monthFormat = new SimpleDateFormat("M");
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));
SimpleDateFormat yearFormat = new SimpleDateFormat("YYYY");
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));
I'm trying to build a calendar view and I'm starting by retrieving the currrent year and month. However, what is returned is a string, whereas I want a int to use in arrays etc..
The code posted above is giving me an error most likely due to the Integer.parseInt function.
Can I not use it? What is the best way of retrieving the year, month, and day.
You can use calander class to get time
This is for default date means current date :
Calendar cal=Calendar.getInstance();
System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+" DAY: "+cal.get(Calendar.DAY_OF_MONTH));
//out put as YEAR:2012 MONTH: 01 DAY: 7
This is specified date :
Date date1=new Date(Long.parseLong("13259152444455"));//or Date date1=new Date(13259152444455L);
cal=Calendar.getInstance();
cal.setTime(date1);
System.out.println("YEAR:"+cal.get(Calendar.YEAR)+" MONTH: "+cal.get(Calendar.MONTH)+1+" DAY: "+cal.get(Calendar.DAY_OF_MONTH));
// output as YEAR:2390 MONTH: 21 DAY: 2
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
int _currentMonth = Integer.parseInt(monthFormat.format(new Date(System.currentTimeMillis())));
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
int _currentYear = Integer.parseInt(yearFormat.format(new Date(System.currentTimeMillis())));
Change "M" to "MM" and "YYYY" to "yyyy".
duh it does work! I have to use yyyy instead of YYYY. The blackberry documentation had it as YYYY