How can the year in the output add up according to the month's summation?
int sewa = 10
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String cyear = Integer.toString(year);
int mont = (now.get(Calendar.MONTH) + 1);
String cmont = Integer.toString(mont);
int day = (now.get(Calendar.DATE) );
String cday = Integer.toString(day);
String date = cyear +"/"+cmont+"/"+cday;
Calendar ex = Calendar.getInstance();
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
ex.add(Calendar.MONTH,+sewa);
int exmont = (ex.get(Calendar.MONTH) + 1);
String excmont = Integer.toString(exmont);
int exday = (ex.get(Calendar.DATE) );
String excday = Integer.toString(exday);
String exdate = excyear +"/"+excmont+"/"+excday;
System.out.println(date);
System.out.println("+++++");
System.out.println(exdate);
now : 2018/3/25
+++++ after:2018/1/25
how ouput :2019/1/25
If you are using Java 8 or newer version, please use LocalDate instead of Calendar class. It's very easy to add days, months and years using methods plusDays(), plusMonths() and plusYears(). It's that simple:
LocalDate today = LocalDate.now();
today.plusDays(20);
today.plusMonths(1);
today.plusYears(5);
LocalDate and LocalDateTime were introduced with JSR-310 as much simpler, straightforward and easy to use replacement of Date and Calendar.
However, if you use older version of java, or need to use Date and Calendar for some other reason, you can increase the number of years the same way you did with the months, using
ex.add(Calendar.YEAR, 5);
You capture the year to a variable ...
int exyear = ex.get(Calendar.YEAR);
String excyear = Integer.toString(exyear);
... right before you add 10 months to the calendar ...
ex.add(Calendar.MONTH,+sewa);
... which causes the excyear remains not updated.
To solve it, give the statements a correct order (Get Calendar -> add the months -> get Strings -> print). Or better using SimpleDateFormat:
Calendar ex = Calendar.getInstance();
ex.add(Calendar.MONTH, sewa);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String exdate = sdf.format(ex.getTime());
System.out.println(exdate);
Prints out:
2019/01/25
Related
I have specific date and i want to find last day number(integer) of month. I am using following code but always return current of date.
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = (Date) sdf.parse(year+"-"+(month<10?("0"+month):month)+"-01");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date dt = (Date) calendar.getTime(); -> dt is return current date always
example: my date = 2018/04/30 and i want to find 30.
I couldnt find answer at site.
Thnx
If using Java 8 (or higher), don't use Calendar. If using Java 6 or 7, you might want to consider using the ThreeTen Backport. In either case, use the Java Time API.
Using Java Time
Since input is int year and int month, use YearMonth.
To find last day number of month, call lengthOfMonth().
To get the date at the end of month, call atEndOfMonth().
Demo
int year = 2020;
int month = 2;
int lastDay = YearMonth.of(year, month).lengthOfMonth();
System.out.println(lastDay);
LocalDate date = YearMonth.of(year, month).atEndOfMonth();
System.out.println(date);
Output
29
2020-02-29
Using Joda-Time
If you don't have Java 8, and already use Joda-Time, do it this way:
Demo
int year = 2020;
int month = 2;
int lastDay = new LocalDate(year, month, 1).dayOfMonth().getMaximumValue();
System.out.println(lastDay);
LocalDate date = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
System.out.println(date);
Output
29
2020-02-29
Using Calendar
If you insist on using Calendar, call getActualMaximum(Calendar.DAY_OF_MONTH) as also mentioned in other answers.
Since input is int year and int month, don't build and parse a string, just set Calendar fields directly. Note that "month" in Calendar is zero-based.
Demo
int year = 2020;
int month = 2;
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(year, month - 1, 1);
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
calendar.set(Calendar.DAY_OF_MONTH, lastDay);
Date date = calendar.getTime();
System.out.println(lastDay);
System.out.printf("%tF%n", date);
Output
29
2020-02-29
have specific date and i want to find last day number(integer) of month
getActualMaximum() is what you are looking for here.
Calendar cal = Calendar.getInstance();
cal.setTime(parsedDate);
cal.getActualMaximum(Calendar.DAY_OF_MONTH);
Calendar calendar =Calendar.getInstance();
calendar.set(Calendar.DATE, 1);
calendar.roll(Calendar.DATE, -1);
int lastDate=calendar.get(Calendar.DATE);
You can use calendar for that, like this:
calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
Or, if you have joda, which is usually better:
DateTime d = new DateTame(dt);
d.dayOfMonth().getMaximumValue();
First, how are you getting the year to be used?
it should be simple by using Java Time LocalDate:
import java.time.*;
import static java.time.Month.*;
import static java.time.temporal.TemporalAdjusters.*;
import static java.time.temporal.ChronoField.*;
int lastDay = LocalDate.now() // or whatever date you want
.with(Month.of(yourMonth))
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);
// or, if you have year and month, and want to find the corresponding last day
int lastDay = LocalDate.of(yourYear, yourMonth, 1)
.with(lastDayOfMonth())
.get(DAY_OF_MONTH);
This question already has an answer here:
Automatically calculate age after focus change [closed]
(1 answer)
Closed 7 years ago.
I have date of birth and can get the current date.
In java, how can I calculate someone's age while taking leap year into account?
Edit: Can I use unix timestamps and compare the difference?
As you may know that java 8 date and time API changes are inspired from Jodatime library itself, so out next solution using java 8 looks almost similar to above code sample:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1960, Month.JANUARY, 1);
Period p = Period.between(birthday, today);
//Now access the values as below
System.out.println(p.getDays());
System.out.println(p.getMonths());
System.out.println(p.getYears());
LocalDate birthdate = new LocalDate (1990, 12, 2);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
In Java 8:
LocalDate startDate = LocalDate.of(1987, Month.AUGUST, 10);
LocalDate endDate = LocalDate.of(2015, Month.MAY, 27);
long numberOfYears = ChronoUnit.YEARS.between(startDate, endDate);
Great examples for using dates with Java 8:
Java 8 Date Examples
As #MadProgrammer has suggested, you could use JodaTime.
Here's the sample code.
LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);
What about:
Date birthDate = new Date(85, 03, 24);
GregorianCalendar birth = new GregorianCalendar();
birth.setTime(birthDate);
int month = birth.get(GregorianCalendar.MONTH);
int day = birth.get(GregorianCalendar.DAY_OF_MONTH);
GregorianCalendar now = new GregorianCalendar();
int age = now.get(GregorianCalendar.YEAR) - birth.get(GregorianCalendar.YEAR);
int birthMonth = birth.get(GregorianCalendar.MONTH);
int birthDay = birth.get(GregorianCalendar.DAY_OF_MONTH);
int nowMonth = now.get(GregorianCalendar.MONTH);
int nowDay = now.get(GregorianCalendar.DAY_OF_MONTH);
if (nowMonth>birthMonth) {
age = age+1;
} else {
if (nowMonth == birthMonth) {
if (nowDay >= birthDay) {
age= age+1;
}
}
}
System.out.println("Now it is my " + age+ " year of life");
I need to get the present year value in string so I did:
Calendar now = Calendar.getInstance();
DateFormat date = new SimpleDateFormat("yyyy");
String year = date.format(now);
It works on ubuntu but it's not working on windows 7.
Do you know why?
Is there a safer way to do that?
Thanks
You can simple get the year from Calendar instance using Calendar#get(int field) method:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
String yearInString = String.valueOf(year);
String thisYear = new SimpleDateFormat("yyyy").format(new Date());
In Java 8 there's a collection called java.time in which you easily can obtain the current year from your computer's clock.
To get the current year as an integer you can simply write:
int thisYear = Year.now().getValue();
To get it as a String:
String thisYear = Year.now().toString();
What about
Date currentDate = new Date();
String currentYear = String.valueOf(currentDate.getYear());
Java 8:
java.time.Year.now();
here is the link.
You can also do it like this:
String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
try
Calendar now = Calendar.getInstance();
String year = String.valueOf(now.get(Calendar.YEAR));
Time Zone
Both the question and accepted answer ignore the question of time zone. At the time of a new year, the year number varies depending on your time zone.
Joda-Time
The bundled java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Time or the new java.time package in Java 8.
Example in Joda-Time.
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTime = DateTime.now( timeZone );
int year = dateTime.year().get();
// enter code here
Date date = new Date();
DateFormat format = new SimpleDateFormat("yyyy");
String year = format.format(date);
In Java versions prior Java 8 you could also use java.sql.Date class. Convert to String and substring the year:
String currentYear = new java.sql.Date(System.currentTimeMillis()).toString().substring(0, 4);
Is there a oneliner to get the name of the month when we know:
int monthNumber = calendar.get(Calendar.MONTH)
Or what is the easiest way?
You can achieve it using SimpleDateFormat, which is meant to format date and times:
Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));
String getMonthForInt(int num) {
String month = "wrong";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (num >= 0 && num <= 11) {
month = months[num];
}
return month;
}
As simple as this
mCalendar = Calendar.getInstance();
String month = mCalendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
This is the solution I came up with for a class project:
public static String theMonth(int month){
String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
return monthNames[month];
}
The number you pass in comes from a Calendar.MONTH call.
If you have multi-language interface, you can use getDisplayName to display the name of month with control of displaying language.
Here is an example of displaying the month name in English, French, Arabic and Arabic in specific country like "Syria":
Calendar c = Calendar.getInstance();
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.ENGLISH ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.FRANCE ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar") ) );
System.out.println(c.getDisplayName(Calendar.MONTH, Calendar.LONG, new Locale("ar", "SY") ) );
System.out.println(c.getTime().toString());
The result is:
January
janvier
يناير
كانون الثاني
Sat Jan 17 19:31:30 EET 2015
SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );
For some languages (e.g. Russian) this is the only correct way to get the stand-alone month names.
This is what you get, if you use getDisplayName from the Calendar or DateFormatSymbols for January:
января (which is correct for a complete date string: "10 января, 2014")
but in case of a stand-alone month name you would expect:
январь
Joda-Time
How about using Joda-Time. It's a far better date-time API to work with (And January means january here. It's not like Calendar, which uses 0-based index for months).
You can use AbstractDateTime#toString( pattern ) method to format the date in specified format:
DateTime date = DateTime.now();
String month = date.toString("MMM");
Month Name From Number
If you want month name for a particular month number, you can do it like this:
int month = 3;
String monthName = DateTime.now().withMonthOfYear(month).toString("MMM");
Localize
The above approach uses your JVM’s current default Locale for the language of the month name. You want to specify a Locale object instead.
String month = date.toString( "MMM", Locale.CANADA_FRENCH );
Month::getDisplayName
Since Java 8, use the Month enum. The getDisplayName method automatically localizes the name of the month.
Pass:
A TextStyle to determine how long or how abbreviated.
A Locale to specify the human language used in translation, and the cultural norms used for abbreviation, punctuation, etc.
Example:
public static String getMonthStandaloneName(Month month) {
return month.getDisplayName(
TextStyle.FULL_STANDALONE,
Locale.getDefault()
);
}
It might be an old question, but as a one liner to get the name of the month when we know the indices, I used
String month = new DateFormatSymbols().getMonths()[monthNumber - 1];
or for short names
String month = new DateFormatSymbols().getShortMonths()[monthNumber - 1];
Please be aware that your monthNumber starts counting from 1 while any of the methods above returns an array so you need to start counting from 0.
This code has language support.
I had used them in Android App.
String[] mons = new DateFormatSymbols().getShortMonths();//Jan,Feb,Mar,...
String[] months = new DateFormatSymbols().getMonths();//January,Februaty,March,...
I found this much easier(https://docs.oracle.com/javase/tutorial/datetime/iso/enum.html)
private void getCalendarMonth(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
Month month = Month.of(calendar.get(Calendar.MONTH));
Locale locale = Locale.getDefault();
System.out.println(month.getDisplayName(TextStyle.FULL, locale));
System.out.println(month.getDisplayName(TextStyle.NARROW, locale));
System.out.println(month.getDisplayName(TextStyle.SHORT, locale));
}
This works for me:
String getMonthName(int monthNumber) {
String[] months = new DateFormatSymbols().getMonths();
int n = monthNumber-1;
return (n >= 0 && n <= 11) ? months[n] : "wrong number";
}
To returns "September" with one line:
String month = getMonthName(9);
Calender cal = Calendar.getInstance(Locale.ENGLISH)
String[] mons = new DateFormatSymbols(Locale.ENGLISH).getShortMonths();
int m = cal.get(Calendar.MONTH);
String mName = mons[m];
Easiest Way
import java.text.DateFormatSymbols;
int month = 3; // March
System.out.println(new DateFormatSymbols().getMonths()[month-1]);
You can get it one line like this:
String monthName = new DataFormatSymbols.getMonths()[cal.get(Calendar.MONTH)]
One way:
We have Month API in Java (java.time.Month). We can get by using Month.of(month);
Here, the Month are indexed as numbers so either you can provide by Month.JANUARY or provide an index in the above API such as 1, 2, 3, 4.
Second way:
ZonedDateTime.now().getMonth();
This is available in java.time.ZonedDateTime.
It returns English name of the month.
04 returns APRIL and so on.
String englishMonth (int month){
return Month.of(month);
}
import java.text.SimpleDateFormat;
import java.util.Calendar;
Calendar cal = Calendar.getInstance();
String currentdate=new SimpleDateFormat("dd-MMM").format(cal.getTime());
I created a Kotlin extension based on responses in this topic and using the DateFormatSymbols answers you get a localized response.
fun Date.toCalendar(): Calendar {
val calendar = Calendar.getInstance()
calendar.time = this
return calendar
}
fun Date.getMonthName(): String {
val month = toCalendar()[Calendar.MONTH]
val dfs = DateFormatSymbols()
val months = dfs.months
return months[month]
}
DateFormat date = new SimpleDateFormat("dd/MMM/yyyy");
Date date1 = new Date();
System.out.println(date.format(date1));
For full name of month:
val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.Long, Locale.ENGLISH)!!.toString()
And for short name of month:
val calendar = Calendar.getInstance()
calendar.timeInMillis = date
return calendar.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.ENGLISH)!!.toString()
from the SimpleDateFormat java doc:
* <td><code>"yyyyy.MMMMM.dd GGG hh:mm aaa"</code>
* <td><code>02001.July.04 AD 12:08 PM</code>
* <td><code>"EEE, d MMM yyyy HH:mm:ss Z"</code>
* <td><code>Wed, 4 Jul 2001 12:08:56 -0700</code>
I have a problem to sort date because of the format of these dates.
I obtain the date :
final Calendar c = Calendar.getInstance();
mYear = c.get(Calendar.YEAR);
mMonth = c.get(Calendar.MONTH);
mDay = c.get(Calendar.DAY_OF_MONTH);
And I build a String with these values.
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
The problem is that if the month is for example February, mMonth value is 2. So dates with months like October (10) comes before in my list.
What I need is that month and day are formated like MM and dd. But I don't know how to do it in my case.
EDIT :
I solved the problem by using a DateFormat like said above.
I replaced this :
dateRappDB = (new StringBuilder()
.append(mYear).append(".")
.append(mMonth + 1).append(".")
.append(mDay).append(" ")).toString();
By this :
Date date = new Date(mYear - 1900, mMonth, mDay);
dateFacDB = DateFormat.format("yyyy.MM.dd", date).toString();
And it works.
Thanks to all of you for your help :)
here is a simple way to convert Date to String :
SimpleDateFormat simpleDate = new SimpleDateFormat("dd/MM/yyyy");
String strDt = simpleDate.format(dt);
Calendar calendar = Calendar.getInstance();
Date now = calendar.getTime();
String timestamp = simpleDateFormat.format(now);
These might come in handy
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ");
this format is equal to --> "2016-01-01T09:30:00.000000+01:00"
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ");
this format is equal to --> "2016-06-01T09:30:00+01:00"
here is the example for date format
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = new Date();
System.out.println("format 1 " + sdf.format(date));
sdf.applyPattern("E MMM dd yyyy");
System.out.println("format 2 " + sdf.format(date));
You need to sort dates, not strings. Also, have you heared about DateFormat? It makes all that appends for you.
If I understand your issue, you create a list of dates and since they're strings, they get arranged in a dictionary-order number-wise, which means you get october before february (10 before 2).
If I were you, I would store my results in a container where I control the insertion point (like an array list) or where I can control the sorting algorithm.