How to get int to a SimpleDateFormat - java

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 :)

Related

How do find day number(integer) of last day in the current month

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);

Formatting java.sql.Date to yyyyMMdd

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 to subtract X day from a Date object in Java?

I want to do something like:
Date date = new Date(); // current date
date = date - 300; // substract 300 days from current date and I want to use this "date"
How to do it?
Java 8 and later
With Java 8's date time API change, Use LocalDate
LocalDate date = LocalDate.now().minusDays(300);
Similarly you can have
LocalDate date = someLocalDateInstance.minusDays(300);
Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime
Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
Java 7 and earlier
Use Calendar's add() method
Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();
#JigarJoshi it's the good answer, and of course also #Tim recommendation to use .joda-time.
I only want to add more possibilities to subtract days from a java.util.Date.
Apache-commons
One possibility is to use apache-commons-lang. You can do it using DateUtils as follows:
Date dateBefore30Days = DateUtils.addDays(new Date(),-30);
Of course add the commons-lang dependency to do only date subtract it's probably not a good options, however if you're already using commons-lang it's a good choice. There is also convenient methods to addYears,addMonths,addWeeks and so on, take a look at the api here.
Java 8
Another possibility is to take advantage of new LocalDate from Java 8 using minusDays(long days) method:
LocalDate dateBefore30Days = LocalDate.now(ZoneId.of("Europe/Paris")).minusDays(30);
Simply use this to get date before 300 days, replace 300 with your days:
Date date = new Date(); // Or where ever you get it from
Date daysAgo = new DateTime(date).minusDays(300).toDate();
Here,
DateTime is org.joda.time.DateTime;
Date is java.util.Date
Java 8 Time API:
Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);
As you can see HERE there is a lot of manipulation you can do. Here an example showing what you could do!
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
//Add one day to current date.
cal.add(Calendar.DATE, 1);
System.out.println(dateFormat.format(cal.getTime()));
//Substract one day to current date.
cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
System.out.println(dateFormat.format(cal.getTime()));
/* Can be Calendar.DATE or
* Calendar.MONTH, Calendar.YEAR, Calendar.HOUR, Calendar.SECOND
*/
With Java 8 it's really simple now:
LocalDate date = LocalDate.now().minusDays(300);
A great guide to the new api can be found here.
In Java 8 you can do this:
Instant inst = Instant.parse("2018-12-30T19:34:50.63Z");
// subtract 10 Days to Instant
Instant value = inst.minus(Period.ofDays(10));
// print result
System.out.println("Instant after subtracting Days: " + value);
I have created a function to make the task easier.
For 7 days after dateString: dateCalculate(dateString,"yyyy-MM-dd",7);
To get 7 days upto dateString: dateCalculate(dateString,"yyyy-MM-dd",-7);
public static String dateCalculate(String dateString, String dateFormat, int days) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat s = new SimpleDateFormat(dateFormat);
try {
cal.setTime(s.parse(dateString));
} catch (ParseException e) {
e.printStackTrace();
}
cal.add(Calendar.DATE, days);
return s.format(cal.getTime());
}
You may also be able to use the Duration class. E.g.
Date currentDate = new Date();
Date oneDayFromCurrentDate = new Date(currentDate.getTime() - Duration.ofDays(1).toMillis());
You can easily subtract with calendar with SimpleDateFormat
public static String subtractDate(String time,int subtractDay) throws ParseException {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
cal.setTime(sdf.parse(time));
cal.add(Calendar.DATE,-subtractDay);
String wantedDate = sdf.format(cal.getTime());
Log.d("tag",wantedDate);
return wantedDate;
}

Formatting date and time

I have a question related to conversion/formatting of date.
I have a date,say,workDate with a value, eg: 2011-11-27 00:00:00
From an input textbox, I receive a time value(as String) in the form "HH:mm:ss", eg: "06:00:00"
My task is to create a new Date,say,newWorkDate, having the same year,month,date as workDate,and time to be the textbox input value.
So in this case, newWorkDate should be equal to 2011-11-27 06:00:00.
Can you help me figure out how this can be achieved using Java?
Here is what I have so far:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
//Text box input is converted to Date format -what will be the default year,month and date set here?
Date textBoxTime = df.parse(minorMandatoryShiftStartTimeStr);
Date workDate = getWorkDate();
int year = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(0, 4));
int month = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(4, 6));
int date = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(6, 8));
Date newWorkDate = DateHelper.createDate(year, month, day);
//not sure how to set the textBox time to this newWorkDate.
[UPDATE]: Thx for the help,guys!Here is the updated code based on all your suggestions..Hopefully this will work.:)
String[] split = textBoxTime.split(":");
int hour = 0;
if (!split[0].isEmpty)){
hour = Integer.parseInt(split[0]);}
int minute = 0;
if (!split[1].isEmpty()){
minute = Integer.parseInt(split[1]);}
int second = 0;
if (!split[2].isEmpty()){
second = Integer.parseInt(split[2]);}
Calendar cal=Calendar.getInstance();
cal.setTime(workDate);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
Date newWorkDate = cal.getTime();
A couple of hints:
Use a Calendar object to work with the dates. You can set the Calendar from a Date so the way you create the dates textBoxTime and workDate are fine.
Set the values of workDate from textBoxTime using the setXXX methods on Calendar class (make workDate a Calendar)
You can use SimpleDateFormat to format as well as parse. Use this to produce the desired output.
You should be able to do this with no string parsing and just a few lines of code.
Since you already have the work date, all you need to do is convert your timebox to seconds and add it to your date object.
Use Calendar for date Arithmetic.
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
Date desiredDate = cal.getTime();
You may need the following code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date workDate = simpleDateFormat1.parse("2011-11-27");
Calendar workCalendar= Calendar.getInstance();
workCalendar.setTime(workDate);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.setTime(simpleDateFormat2.parse("06:00:00"));
workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
Date newWorkDate = workCalendar.getTime();
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
System.out.println(simpleDateFormat3.format(newWorkDate));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this would help you.

Julian Date Conversion

Sample Julian Dates:
2009218
2009225
2009243
How do I convert them into a regular date?
I tried converting them using online converter and I got-
12-13-7359 for 2009225!! Makes no sense!
Use the Joda-Time library and do something like this:
String dateStr = "2009218";
MutableDateTime mdt = new MutableDateTime();
mdt.setYear(Integer.parseInt(dateStr.subString(0,3)));
mdt.setDayOfYear(Integer.parseInt(dateStr.subString(4)));
Date parsedDate = mdt.toDate();
Using the Java API:
String dateStr = "2009218";
Calendar cal = new GregorianCalendar();
cal.set(Calendar.YEAR,Integer.parseInt(dateStr.subString(0,3)));
cal.set(Calendar.DAY_OF_YEAR,Integer.parseInt(dateStr.subString(4)));
Date parsedDate = cal.getTime();
---- EDIT ----
Thanks for Alex for providing the best answer:
Date myDate = new SimpleDateFormat("yyyyD").parse("2009218")
Another format is CYYDDDD I wrote this function in Java
public static int convertToJulian(Date date){
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
String syear = String.format("%04d",year).substring(2);
int century = Integer.parseInt(String.valueOf(((year / 100)+1)).substring(1));
int julian = Integer.parseInt(String.format("%d%s%03d",century,syear,calendar.get(Calendar.DAY_OF_YEAR)));
return julian;
}

Categories