How to convert from Date to Int [duplicate] - java

This question already has answers here:
How to Convert Date to Int? [closed]
(2 answers)
Closed 9 years ago.
I'm Trying to get the current day value (example. 12) then assign it to a variable (example. today= 12).
DateFormat DateFormat= new SimpleDateFormat ("dd");
//get current day time with Date()
Date day= new Date ();
int day1 = Integer.valueOf(day);
Or
DateFormat DateFormat= new SimpleDateFormat ("dd");
//get current day time with Date()
Date day= new Date ();
int day1 = day;
But it didn't work :(
There's another way?
Sorry for not clearing the meaning enough in my preview question :)

Apart from #R.J answer, you can use a Calendar and get the day:
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int day = calendar.get(Calendar.DATE);

You can do something like this
int day1 = Integer.valueOf(DateFormat.format(day));
But I must say the naming convention is very bad.

Related

Increment in date choosen from JDateChooser [duplicate]

This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 4 years ago.
I am stuck in a programming issue. I am am making Java Application in Eclipse attached with SQlite. I want such state where user choose a date from JDateChooser and date of after two days from the specified one in JDateChooser show into next field.
I am using the following code which I know works..
DateFormat df=new SimpleDateFormat("dd-MM-yyyy");
Date date = df.parse(ArrivalDate);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, 2); // Add 30 days
Date futureDate = cal.getTime();
String NextDate=df.format(futureDate);
----Here ArrivalDate is date entered by user.
Issue over here is this, that Calender class choose the present date of the day. Not work with the date choose by the user.
For example, if today date is 01/08/2018 and user has entered 12/08/2018.. This code will give 03/08/2018 in return, not the 14/08/2018. How do I achieve this scenario?? Kindly help.
Using LocalDate and DateTimeFormmatter instead of Date and Calendar can be done like this:
public static void main(String[] args) {
String arrivalDate = "12/08/2018";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate arrival = LocalDate.parse(arrivalDate, formatter);
LocalDate futureDay = arrival.plusDays(2);
String nextDate = futureDay.format(formatter);
System.out.println("Arrival: " + arrivalDate);
System.out.println("Next Day: " + nextDate);
}
The output:
Arrival: 12/08/2018
Next Day: 14/08/2018

How to do subtraction from a particular date using Java [duplicate]

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 4 years ago.
I am encountering an issue which is related to Java Date Function.
I'm getting the date from Application (example: 6/5/18) which is in MM/DD/YY format. Now I need to do -2 from the date. I know how to do -2 from current system date using calendar object (see the below code).
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
info("Date is displayed as : "+ PastDate );
I'm not able to put the date which I'm getting from Application in this format. Can someone please help me? (Any other way to do it would also be fine)
I suggest you to use Java 8 compatible Date and Time types.
If you use java.time.LocalDate then this is the solution:
LocalDate.now().minusDays(2)
From your question, it seems that you have the challenge in dealing with formatting, and then doing the subtraction.
I would recommend Java Date and Time Apis for this purpose, using a formatter.
A junit method to achieve your requirement is given below
#Test
public void testDateFormatUsingJava8() {
CharSequence inputdateTxt = "6/5/18";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("M/d/yy");
LocalDate inputDate = LocalDate.parse(inputdateTxt, formatter);
System.out.println(inputDate.minusDays(2L).format(formatter));
}
#Test
public void testDateCalenderUsingStringSplit() {
String inputdateTxt = "6/5/18";
String[] dateComponenets = inputdateTxt.split("//");
Calendar cal = Calendar.getInstance();
//Know where are the year month and date are stored.
cal.set(Integer.parseInt(dateComponenets[2]), Integer.parseInt(dateComponenets[0]), Integer.parseInt(dateComponenets[2]) );
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
}
#Test
public void testDateCalenderUsingJavaUtilDateApi() throws ParseException {
String inputdateTxt = "6/5/18";
DateFormat dateFormat = new SimpleDateFormat("M/d/yy");
Date date = dateFormat.parse(inputdateTxt);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE,-2);
String pastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ pastDate );
The reason why I use "M/d/yy" is because your question does not pad the date and month fields in the input date with a zero. If there is a guarantee that you receive a padded value in the date and month field, using "MM/dd/yy" is suggested.
See the following answer for your reference :
DateTimeFormatterSupport for Single Digit Values
EDIT: considering the limitation to not use Java 8 Date Time APIs, I have added two other alternatives to solve the problem. The OP is free to choose any one of the solutions. Kept the Java 8 solution intact for information purposes.
Calendar cal = Calendar.getInstance();
cal.set(2018, 5, 6); // add this, setting data from the value you parsed
cal.add(Calendar.DATE,-2);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
String PastDate = dateFormat.format(cal.getTime());
System.out.println("Date is displayed as : "+ PastDate);

How to get day of year as an integer with simpledateformat? [duplicate]

This question already has answers here:
Today is nth day of year [duplicate]
(6 answers)
Julian day of the year in Java
(9 answers)
Closed 4 years ago.
I have a simple program that asks a user to enter a date in a MM-dd-yyyy format. How can I get the day of the year from this input? For example if the user enters "06-10-2008" the day of the year would be the 162nd day considering this was a leap year.
Here's my code so far:
System.out.println("Please enter a date to view (MM/DD/2008):");
String date = sc.next();
SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");
Date date2=null;
try {
//Parsing the String
date2 = dateFormat.parse(date);
} catch (ParseException e) {
System.out.println("Invalid format, please enter the date in a MM-dd-yyyy format!");
continue;
} //End of catch
System.out.println(date2);
}
Assuming you are using Java 8+, you could use the LocalDate class to parse it with a DateTimeFormatter like
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("MM-dd-yyyy");
System.out.println(LocalDate.parse("06-10-2008", fmt).getDayOfYear());
Outputs (as requested)
162
Like this
Calendar cal = Calendar.getInstance();
cal.setTime(date2); //Assuming this is date2 variable from your code snippet
int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
Calendar c = Calendar.getInstance();
c.setTime(date2);
System.out.println("Day of year = " + c.get(Calendar.DAY_OF_YEAR));

Java get current day from unix timestamp [duplicate]

This question already has answers here:
Java: Date from unix timestamp
(11 answers)
Closed 5 years ago.
I want to convert unix timestamp to only the current day, like the current day of the month of current day of the year, is it possible to do only using math, like *, /, or something?
The short solution is something like
long epoch = 1501350790; // current unix time
int day = Integer.parseInt(new SimpleDateFormat("dd").format(new Date(epoch * 1000L)));
it is possible to get this result by calculation (* and /) but there is no easy way. you can use the implementation of java.util.GregorianCalendar as reference
You can use SimpleDateFormat to format your date:
long unixSeconds = 1372339860;
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); // the format of your date
sdf.setTimeZone(TimeZone.getTimeZone("GMT-4")); // give a timezone reference for formating (see comment at the bottom
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
You can also convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);
After doing it, you can get what you want:
Calendar cal = Calendar.getInstance();
cal.setTime(dateTime);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH); //here is what you need
int day = cal.get(Calendar.DAY_OF_MONTH);
You can calculate the date from a unix timestamp with java.util.Date
You need to multiply the timestamp with 1000, because java expects milliseconds. You can use the cal.get(Calendar.DAY_OF_MONTH) function to print the day.
import java.sql.Timestamp;
import java.util.Calendar;
public class MyFirstJavaProgram {
public static void main(String []args) {
long unixTimeStamp= System.currentTimeMillis() / 1000L;
java.util.Date time=new java.util.Date((long)unixTimeStamp*1000);
Calendar cal = Calendar.getInstance();
// It's a good point better use cal because date-functions are deprecated
cal.setTime(time);
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
}
}
Any further questions please leave a comment.

How to get date in days only Java? [duplicate]

This question already has answers here:
How to get day of year number in Java for a specific date object? [duplicate]
(3 answers)
Today is nth day of year [duplicate]
(6 answers)
Closed 5 years ago.
Is there a way to get the date in java in days only? For instance Jan 1 would equal 1 and Feb 1 would equal 32? Instead of the standard time format yyyy/mm/dd?
Perhaps by editing the date formater somehow:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate localDate = LocalDate.now();
Use getDayOfYear():
LocalDate localDate = LocalDate.now();
System.out.println(localDate.getDayOfYear());
Returns: the day-of-year, from 1 to 365, or 366 in a leap year
You can use below
Calendar calendar = Calendar.getInstance();
int dayOfYear = calendar.get(Calendar.DAY_OF_YEAR);
int day = LocalDate.getDayOfYear();
try this
SimpleDateFormat format1=new SimpleDateFormat("MM/dd/yyyy");
Date dt1=format1.parse(pass your date);
DateFormat format2=new SimpleDateFormat("EEEE");
String finalDay=format2.format(dt1);

Categories