I have a string like "1512". I need to convert it to a date 2015-12-31 23:59:59.
In that case, I am using Java Dateformat parse.
My code:
private static final dateformat = new SimpleDateFormat("yyMM");
public static boolean checkDate(String date){
Date date = dateformat.parse(date);
}
It can give date upto 20 years. When date is "3610", it gives, 1936, instead of 2036 (of the current century).
I think, you can manually parse the String and then create the Date object.
suppose:
public static void checkDate(String date) throws ParseException {
Calendar calendar = Calendar.getInstance();
int year = Integer.parseInt(date.substring(0, 2));
int month = Integer.parseInt(date.substring(2, 4));
calendar.setLenient(false);
int yearOfCentury = calendar.get(Calendar.YEAR);
int century = yearOfCentury - yearOfCentury % 100;
year = year + century;
calendar.set(Calendar.YEAR, year);
calendar.set(Calendar.MONTH, month-1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
System.out.println("Date +" + calendar.getTime());
}
If you are sure that the year should be always 2000+ then prefix the string with "20" manually and use the SimpleDateFormat as
private static final dateformat = new SimpleDateFormat("yyyyMM");
From the docs:
For parsing with the abbreviated year pattern ("y" or "yy"),
SimpleDateFormat must interpret the abbreviated year relative to some
century. It does this by adjusting dates to be within 80 years before
and 20 years after the time the SimpleDateFormat instance is created.
For example, using a pattern of "MM/dd/yy" and a SimpleDateFormat
instance created on Jan 1, 1997, the string "01/11/12" would be
interpreted as Jan 11, 2012 while the string "05/04/64" would be
interpreted as May 4, 1964.
The default behaviour of the YearMonth parser in Java 8 for 2 digit years is to start from 2000. So this would give you the result you expect:
YearMonth ym = YearMonth.parse("3610", DateTimeFormatter.ofPattern("yyMM"));
//ym = 2036-10
If you want a cut-off at a specific date (say you want 80-99 to be 1980-1999 and 0-79 to be 2000-2079) you can use a custom pattern.
Related
I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);
I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();
This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.
Current Java:
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;
private void setDateOfOrder()
{
//Get current date time with Date()
dateOfOrder = new Date();
}
public Date getDateOfOrder()
{
return dateOfOrder;
}
Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.
Use Calendar and set the current time then user the add method of the calendar
try this:
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 2 week to the current date
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
System.out.println("Next week: " + next2Week);
}
}
The output:
Current date: 2016-08-15
Next week: 2016-08-29
Java 8 rocks !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-
For getting last date of month I have written this function
/**
* #param month integer value of month
* #param year integer value of month
* #return last day of month in MM/dd/YYYY format
*/
private static String getDate(int month, int year) {
Calendar calendar = Calendar.getInstance();
// passing month-1 because 0-->jan, 1-->feb... 11-->dec
calendar.set(year, month - 1, 1);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
Date date = calendar.getTime();
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/YYYY");
return DATE_FORMAT.format(date);
}
for all the inputs its working fine with one exception when the month is December, i.e. getDate(12, 2012) returns 12/31/2013 but it should return 12/31/2012.
Please explain the behavior and solution too.
Change YYYY to yyyy
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
YYYY is wrong dateformat
Try this
calendar.add(Calendar.MONTH, month);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
Date date = calendar.getTime();
Try to use Joda-Time, it's more simple :
private static String getLastDayOfMonth(int month, int year) {
LocalDate lastDayOfMonth = new LocalDate(year, month, 1).dayOfMonth().withMaximumValue();
return lastDayOfMonth.toString("MM/dd/yyyy");
}
tl;dr
YearMonth.of( 2016 , 6 )
.atEndOfMonth()
.toString()
2016-06-30
java.time
Very easy with the java.time classes built into Java 8 and later. Back-ported to Java 6 & 7, and further adapted to Android.
YearMonth
Use the handy YearMonth class.
Tip: Pass objects of this class around your code base rather than mere integers to benefit from type-safety, guaranteed valid values, and more self-documenting code.
YearMonth yearMonth = YearMonth.of( 2016 , 6 );
…or…
YearMonth yearMonth = YearMonth.of( 2016 , Month.JUNE );
LocalDate
Then ask for the last day of that month, represented by LocalDate.
LocalDate endOfMonth = yearMonth.atEndOfMonth();
2016-06-30
Strings
The result of toString you see above, where a String was generated using standard ISO 8601 formatting. You can use other formatting.
The DateTimeFormatter class can automatically translate to a human language and apply cultural norms to issues such as period versus comma or the ordering of year-month-day parts.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT );
formatter = formatter.withLocale( Locale.US ); // Re-assign JVM’s current default Locale that was implicitly applied to the formatter.
String output = localDate.format( formatter );
The Locale.US gives us a month/day/year format. You can also specify an explicit pattern by calling DateTimeFormatter.ofPattern.
private static String getDate(int month, int year) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, month);
calendar.set(Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
Date date = calendar.getTime();
DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy");
return DATE_FORMAT.format(date);
}
You can use the following code to get last day of the month
public static String getLastDayOfTheMonth(String date) {
String lastDayOfTheMonth = "";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
try{
java.util.Date dt= formatter.parse(date);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dt);
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DATE, -1);
java.util.Date lastDay = calendar.getTime();
lastDayOfTheMonth = formatter.format(lastDay);
} catch (ParseException e) {
e.printStackTrace();
}
return lastDayOfTheMonth;
}
With Java 8 DateTime / LocalDateTime :
private static String getDate(int month, int year) {
Month monthObj = Month.of(month);
LocalDate date = LocalDate.of(year, month, monthObj.maxLength());
return date.format(DateTimeFormatter.ofPattern("MM/dd/yyyy", Locale.US));
}
Try this
private static String getDate(int month, int year)
{
Calendar dateCal = Calendar.getInstance();
dateCal.set(year, month, 2);
int maxDay = dateCal.getActualMaximum(Calendar.DAY_OF_MONTH);
String pattern = "MMMM";
SimpleDateFormat obDateFormat = new SimpleDateFormat(pattern);
String monthName = obDateFormat.format(dateCal.getTime());
return "Last date of " + monthName + " " + year + " : " + maxDay;
}
Are you considering leap year as well here? if not then you can try below code:
public static Date calculateMonthEndDate(int month, int year) {
int[] daysInAMonth = { 29, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = daysInAMonth[month];
boolean isLeapYear = new GregorianCalendar().isLeapYear(year);
if (isLeapYear && month == 2) {
day++;
}
GregorianCalendar gc = new GregorianCalendar(year, month - 1, day);
Date monthEndDate = new Date(gc.getTime().getTime());
return monthEndDate;
}
How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));