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);
Related
I have to implement the below requirement :
The data which will be provided are as follows:
year - for example (1997)
no of days passed - for example (365)
Using above data I have to find out that on which date 365 days of the year 1997 passed.
Here the answer will be : 1997-31-12 (31st Dec 1997).
Is there any shortcut to get this value ?
You can use calendar class for this purpose, YEAR and DAY_OF_YEAR are passed as your parameters:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1997);
cal.set(Calendar.DAY_OF_YEAR, 365);
System.out.println(cal.getTime());
You can format it to your liking as well:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-dd-MM");
System.out.println(dateFormat.format(cal.getTime()));
Output:
1997-31-12
Using JodaTime:
DateTime from = new DateTime(1997, 1, 1, 0, 0); // 1997-01-01T00:00:00
DateTime to = from.plusDays(365);
// then you can print "to", use it...
Using JodaTime:
String date = new LocalDate(1997, 1, 1).plus(Days.days(365-1)).toString("yyyy-MM-dd");
System.out.println(date);
With threeten (jodatime's successor) or Java 8, you can write:
LocalDate result = LocalDate.of(1997,1,1).withDayOfYear(365);
How to get month from a date in java :
DateFormat inputDF = new SimpleDateFormat("mm/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
This code return day and year but not month.
output :
0 - 30 - 2011
This is because your format is incorrect: you need "MM/dd/yy" for the month, because "mm" is for minutes:
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
Prints 8 - 30 - 2011 (because months are zero-based; demo)
First, you used mm in your date format, which is "minutes" according to the Javadocs. You set the minutes to 9, not the month. It looks like the month defaults to 0 (January).
Use MM (capital 'M's) to parse the month. Then, you will see 8, because in Calendar months start with 0, not 1. Add 1 to get back the desired 9.
The first month of the year in the Gregorian and Julian calendars is
JANUARY which is 0
// MM is month, mm is minutes
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
and later
int month = cal.get(Calendar.MONTH) + 1; // To shift range from 0-11 to 1-12
If you read the SimpleDateFormat javadoc, you'll notice that mm is for minutes. You need MM for month.
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Otherwise the format doesn't read a month field and assumes a value of 0.
Month format should be MM instead of mm
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Time for someone to provide the modern answer. The other answers were good answers when the question was asked in 2013 and are still correct. Today there is no reason why you should struggle with the old, outdated and simultaneously notoriously troublesome SimpleDateFormat class. java.time, the modern Java date and time API, is so much nicer to work with:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate date1 = LocalDate.parse("9/30/11", inputFormatter);
System.out.println(date1);
This prints
2011-09-30
The LocalDate class represents a date without time-of-day, exactly what you need, it matches your requirement much more precisely than the old classes Date and Calendar.
The format pattern strings used with DateTimeFormatter resemble those from SimpleDateFormat, there are a few differences. You may use uppercase MM to require two-digit month (like 09 for September) or a single M to allow the month to be written with one or two digits. Similarly dd or d for day of month. yy denotes two-digit year and is interpreted with base 2000, that is, from 2000 to 2099 inclusive (wouldn’t work for my birthday).
Link: Oracle tutorial Trail: Date Time explaining how to use java.time.
Try like this using MM instead of mm:-
DateFormat inputDF = new SimpleDateFormat("MM/dd/yy");
Date date1 = inputDF.parse("9/30/11");
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
System.out.println(month+" - "+day+" - "+year);
The month printed will be 8 as index starts from 0
or try with:-
int month = cal.get(Calendar.MONTH) + 1;
mmis for minutes, use MM while specifying format.
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
int month = cal.get(Calendar.MONTH);// returns month value index starts from 0
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()));
I would like the time respresented as this "Thu Jan 01 08:40:38 GMT+01:00 1754"
so i did this :
Date datu = new Date();
datu.setYear(1754);
datu.setMonth(0);
datu.setDate(1);
DateFormat.format("%tc", datu);
// DATU = Thu Jan 01 08:40:38 GMT+01:00 3654
String startTime = datu.toGMTString();
now the problem is that i set the year on 1754 in the code. but as I print it out. there is 3654 ?
EDIT:
datu.setYear(1754-1900) can do the trick. but isn't there another way?
Please try like this :
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd hh:mm:ss 'GMT'Z yyyy");
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,1754);
c.set(Calendar.MONTH, 0); // JAN
c.set(Calendar.DATE, 1);
System.out.println(sdf.format(new Date(c.getTimeInMillis())));
Output
Tue Jan 01 05:23:55 GMT+0800 1754
What version of the Java API are you using?
I would suggest you use the java.text.SimpleDateFormat and java.util.Calendar instead.
You code would look something like this:
Calendar cal = Calendar.getInstance();
cal.set(1754, 0, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // <- customize your format
sdf.format(cal.getTime()); // <- get your string
The date.toGMTString() method is also deprecated so it's best to avoid it.
It seems that date.SetYear is deprecated. According to the documentation you should use Calendar.set(Calendar.YEAR, year) instead.
As you said, date.setYear(desired year-1900) fixes the problem. It is noteworthy that the method is deprecated it is better you use the Calendar class which doesnt require subtracting 1900 from the year. A code snippet that will achieve what you are doing using Calendar is giving below:
Calendar calendar =Calendar.getInstance();
calendar.setTime(date);// note that the date object here will be datu according to
//your code. It could be any object of the Date class
int year = calendar.get(Calendar.YEAR);
Hope this helps.
Feel free to mark as answer if it solves your problem.
Good luck!
I have a string (Jan12) (generated by applying some operations on current date {20-jan-2012}) Now i want to convert back this string into Date format . Also the value should be same i.e the new Date object should have value jan12 and not (20-jan-2012) . Pls help . I have tried doing
java.sql.Date.valueOf("Jan12") [this throws IllegalArgumentException]
and also
new SimpleDateFormat("MMMyy").parse("Jan12") [By this Date gets converted to 20-jan-2012]
Output required : A Date Object having value Jan12 (12 is the year)
My Code : new java.text.SimpleDateFormat("MMMyy").format(new java.text.SimpleDateFormat("yyyy-MM-dd").parse(s)) // It is a string which gives Jan12
Now i really want to convert Mycode into a Date object
Date now = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String s1 = df.format(now);
System.out.println(s1); // 2012-01-20
java.sql.Date d111=java.sql.Date.valueOf(s1);
System.out.println(d111); // 2012-01-20
DateFormat df1 = new SimpleDateFormat("MMMyy");
String s2 = df1.format(d111);
System.out.println(s2); //Jan12
Now i want s2 to be converted in Date object
#Aditya,
If you use the Str2 which gives "Jan12", there is no date part in that string and therefore if you convert it to a date object, it will get "Jan" as month, 12 as year but it cant find "day" in that String.
if you use below code
try
{
Date d2 = df1.parse(s2); //here s2 is your string which gives "JAN12"
System.out.println(d2);
}
catch(ParseException pe)
{
System.out.println("parse exception..");
}
The output to the above code will be:
Sun Jan 01 00:00:00 IST 2012
notice here that day part is reset to the first day of the month
Therefore, it is not possible to get a complete date object as your original Date, the month and year are preserved, but the day part is lost.
What do you mean "gets converted"? How your Date is displayed is a separate issue. Look into formatting a Date.
So the 12 is day, not a year - you should parse it as such. Aslo, you'll need to tell it what year this is:
System.out.println(new SimpleDateFormat("yyyyMMMdd").parse("2012" + "Jan12"));
Output
Thu Jan 12 00:00:00 EST 2012
Use the SimpleDateFormat class properly, it will do exactly what you want
String str_date="12-Jan-2012";
DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse(str_date);
Note: the formatter.parse() method throws ParseException, catch it;
If 12 is a year
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMyy").parse("Jan12"));
calendar.set(Calendar.DATE, 1);
Date date = calendar.getTime(); // First Jan 2012
If 12 is a day
Calendar calendar = Calendar.getInstance();
calendar.setTime(new SimpleDateFormat("MMMdd").parse("Jan12"));
calendar.set(Calendar.YEAR, 2012);
Date date = calendar.getTime(); // 12 Jan 2012
I understand that you want to format your Date object into a String representation.
You can use SimpleDateFormat for this, analog to your second example:
Date d = new Date(112, 0, 20); //don't construct a date like this in production code, use a Calendar instance instead
String formattedDate = new SimpleDateFormat("MMMyy").format(d); // -> "Jan12"
Note that your Date object represents a specific point in time, it will always have a day and a time associated with it.
If you want to compare Dates with the resolution of a month, you have to set day and time to neutral values:
Calendar cal = Calendar.getInstance();
cal.setTime(d);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
d = cal.getTime();
Just extend Date and customize it to use your favourite parse & format methods.