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.
Related
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 :)
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:
public String getCurrentDate() {
/// get date
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
Date date = new Date();
System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
return dateFormat.format(date);
}
On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.
Are testing with real devices?
You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)
Check the Example bellow:
Calendar current_time_cal = Calendar.getInstance();
current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
int hours = current_time.get(Calendar.HOUR);
int current_am_pm = current_time.get(Calendar.AM_PM);
current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
current_time_cal.set(Calendar.SECOND, 0);
Try this:
Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
You can use this method to get current time from your device:
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String date = sdf.format(calendar.getTime());
return date;
}
This method will return current date as string.
I try to subtract one day when the time inside 0:00 am - 12:00 am.
ex: 2012-12-14 06:35 am => 2012-12-13
I have done a function and It's work. But my question is any other better code in this case? Much simpler and easy to understand.
public String getBatchDate() {
SimpleDateFormat timeFormatter = new SimpleDateFormat("H");
int currentTime = Integer.parseInt(timeFormatter.format(new Date()));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
String Date = dateFormatter.format(new Date());
if ( 0 <= currentTime && currentTime <= 12){
try {
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(dateFormatter.parse(Date));
shiftDay.add(Calendar.DATE, -1);
Date = dateFormatter.format(shiftDay.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("BatchDate:", Date);
}
return Date;
}
THANKS,
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(new Date())
if(shiftDay.get(Calendar.HOUR_OF_DAY) <= 12){
shiftDay.add(Calendar.DATE, -1);
}
//your date format
Use the Calendar class to inspect and modify the Date.
Calendar cal = new GregorianCalendar(); // initializes calendar with current time
cal.setTime(date); // initializes the calender with the specified Date
Use cal.get(Calendar.HOUR_OF_DAY) to find out the hour within the day.
Use cal.add(Calendar.DATE, -1) to set the date one day back.
Use cal.getTime() to get a new Date instance of the time that was stored in the calendar.
As with nearly all questions with regard to Date / Time, try Joda Time
public String getBatchDate() {
DateTime current = DateTime.now();
if (current.getHourOfDay() <= 12)
current = current.minusDays(1);
String date = current.toString(ISODateTimeFormat.date());
Log.d("BatchDate:" + date);
return date;
}
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;
}
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
The following function produces today's date; how can I make it produce only yesterday's date?
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date).toString();
}
This is the output:
2012-07-10
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
https://ideone.com/91M1eU
Outdated answer
You are subtracting the wrong number:
Use Calendar instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
IDEOne Demo
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
Try this;
public String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar by subtracting -1.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));