I have a date object myDate(say).
After doing the following:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
I want to set the myDate object to the above values and hence show the below output.
Mon Sep 09 13:45:52 PST 2013
Please let me know how to do it.
import java.util.*;
public class DateTest {
public static void main(String[] args) {
Date myDate;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
myDate = cal.getTime();
System.out.println(myDate);
}
}
The months attribute starts from January = zero. Why oh why did Sun do such a counter-intuitive thing, I don't know.
import java.util.*;
public class DateTest {
public static void main(String[] args) {
Date myDate;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 8);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);
myDate = cal.getTime();
System.out.println(myDate);
}
}
One other consideration, the output has a timezone in it - if you want the timezone of the Java installation, no probs. If you want PST and the Java timezone default is somewhere else, then use the following constructor:
TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cal = Calendar.getInstance(timezone);
You can write:
myDate.setTime(cal.getTimeInMillis());
Using SimpleDateFormat:
new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").format(cal.getTime())
Related
I want to set datetime of day as: startDate=2018/03/28 00:00:00 and endDate=2018/03/28 23:59:59
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
Date startDate = sdf1.parse(str1);
Date endDate = sdf2.parse(str2);
My problem:program is working and output endDate=2018/03/28 00:00:00
Would you please point out any mistakes to me in code?
update:
i used debug and it's working correct with
String str2=sdf2.format(cal.getTime());//2018-03-28 23:59:59
but when change string==>date is not correct with output 2018/03/28 00:00:00
If you want to initialize Date instances from a formatted string with both date and time then time codes should be added to the SimpleDateFormat pattern to parse strings in that format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startDate = sdf.parse("2018-03-28 00:00:00");
Date endDate = sdf.parse("2018-03-28 23:59:59");
If you want to simply set the hour, minute, and second on the current date then use a Calendar instance and set fields on it accordingly.
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0)
Date startDate = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999)
Date endDate = cal.getTime();
And next output the Date in a particular format:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
System.out.println(sdf.format(startDate));
System.out.println(sdf.format(endDate));
Output:
2018/03/28 00:00:00
2018/03/28 23:59:59
Dealing with time zones
If time zone is other than the local time zone then it's a good idea to be explicit with what timezone you're working with. Calendar and SimpleDateFormat instances must be consistent with what timezone you're dealing with or the date and/or times may be off.
TimeZone utc = TimeZone.getTimeZone("UTC");
Calendar cal = Calendar.getInstance(utc);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
sdf.setTimeZone(utc);
A substitute for SimpleDateFormat is using DateTimeFormatter class found in the newer java.time package added to Java 8.
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
try {
Date startDate = sdf3.parse(str1);
Date endDate = sdf3.parse(str2);
System.out.println(str1);
System.out.println(str2);
System.out.println(startDate.toString());
System.out.println(endDate.toString());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OUT PUT
2018-03-28 00:00:00
2018-03-28 23:59:59
Wed Mar 28 00:00:00 ICT 2018
Wed Mar 28 23:59:59 ICT 2018
I think, maybe sdf1 and sdf2 don't provide clear format.
So change time to HH:mm:ss.
If you just want to get the Date values for today's start and end times, you don't need to use date formatting utilities (like SimpleDateFormat) at all:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.clear(Calendar.MINUTE);
cal.clear(Calendar.SECOND);
cal.clear(Calendar.MILLISECOND);
Date startDate = cal.getTime();
cal.set(Calendar.HOUR_OF_DAY, 23);
cal.set(Calendar.MINUTE, 59);
cal.set(Calendar.SECOND, 59);
cal.set(Calendar.MILLISECOND, 999);
Date endDate = cal.getTime();
You can solve this problem like this
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
String str1=sdf1.format(cal.getTime());
String str2=sdf2.format(cal.getTime());
Date startDate = sdf1.parse(str1);
Date endDate = sdf2.parse(str2);
String startDateTime = sdf1.format(startDate);
String endDateTime = sdf2.format(endDate);
System.out.println("startDate ----->" + startDateTime);
System.out.println("endDate ----->" + endDateTime);
The output of this
startDate ----->2018-03-28 00:00:00
endDate ----->2018-03-28 23:59:59
Hope this is what you want.
I'm trying to get flights for 8 days starting from Sunday to the next Sunday.
The way I have implemented it now is by displaying the 7 days starting the selected date from my form.
// set up calendar for sunday
Calendar sunday = Calendar.getInstance();
sunday.setTime(form.getDate());
sunday.add(Calendar.DAY_OF_WEEK, -1 * (sunday.get(Calendar.DAY_OF_WEEK) - 1));
//set up calendar for next saturday
Calendar saturday = Calendar.getInstance();
saturday.setTime(sunday.getTime());
saturday.add(Calendar.DAY_OF_WEEK, 7);
Since the max of DAY_OF_WEEK is 7, what do I need to use instead?
I tried changing this line:
saturday.add(Calendar.DAY_OF_WEEK, 7);
to the following one:
saturday.add(Calendar.DATE, 8);
I already tried couple changes but no luck.
Any advice?
Try using Calendar.DAY_OF_YEAR.
import java.text.*;
import java.util.*;
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm:ss a z");
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Set day of week to Sunday.
System.out.println(dateFormat.format(sunday.getTime()));
sunday.add(Calendar.DAY_OF_YEAR, 7); // Add seven days.
System.out.println(dateFormat.format(sunday.getTime()));
Output
Sun, Dec 04, 2016 11:47:32 PM EST
Sun, Dec 11, 2016 11:47:32 PM EST
You can create new calendar objects without modifying the existing one, by making a copy.
import java.text.*;
import java.util.*;
public class CalendarUtils {
public static void main(String[] args) {
Calendar sunday = CalendarUtils.getThisSundaysDate();
Calendar saturday = CalendarUtils.daysFrom(sunday, 6);
CalendarUtils.printDates(sunday, saturday);
}
public static Calendar getThisSundaysDate() {
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return sunday;
}
public static Calendar daysFrom(Calendar cal, int days) {
Calendar newCal = copyCalendar(cal);
newCal.add(Calendar.DAY_OF_YEAR, days);
return newCal;
}
public static Calendar copyCalendar(Calendar cal) {
Calendar copy = new GregorianCalendar();
copy.setTime(cal.getTime());
return copy;
}
public static void printDates(Calendar from, Calendar to) {
DateFormat dateFormat = new SimpleDateFormat("EEE, MMMM dd, yyyy hh:mm:ss a z");
System.out.println(dateFormat.format(from.getTime()));
System.out.println(dateFormat.format(to.getTime()));
}
}
If you're using Java 8, you should use the new java.time classes. In this case, you'd want to use the LocalDate class, and the TemporalAdjusters class, with it's previous(DayOfWeek) method.
Alternatively, use the previousOrSame(DayOfWeek), depending on what should happen if the reference date is a Sunday.
Example, using today as the reference date:
LocalDate refDate = LocalDate.now();
LocalDate prevSunday = refDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
LocalDate nextSunday = prevSunday.plusDays(7);
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
System.out.println("Ref. Date: " + refDate.format(fmt));
System.out.println("Prev. Sunday: " + prevSunday.format(fmt));
System.out.println("Next. Sunday: " + nextSunday.format(fmt));
Output
Ref. Date: Monday, December 5, 2016
Prev. Sunday: Sunday, December 4, 2016
Next. Sunday: Sunday, December 11, 2016
I am trying to find out the specific date from a given input string, which can be like "201411W3". I know that the week is 3rd from this string(W3) and the event will be on Friday, so I want to find the date of the 3rd Friday. I did something like this:
public static Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month, 1 );
cal.add( Calendar.DAY_OF_MONTH, - ( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 8 ) );
return cal.getTime();
}
when I call this method: getLastFriday(11, 2014), I get the value "Fri Nov 21 13:16:57 EST 2014" which I need to parse to find out the date. is there any way to get just the date from the result?
Thanks!
If I understood you, then you can use below code as reference -
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test{
public static void main (String[] args)
{
String str="201411W3";
String[] strSplitted = str.split("W");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(strSplitted[0].substring(4,6))-1);
calendar.set(Calendar.YEAR, Integer.parseInt(strSplitted[0].substring(0,4)));
calendar.set(Calendar.DAY_OF_MONTH, 1);
if(calendar.get(Calendar.DAY_OF_WEEK)==7)
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1])+1);
}
else
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1]));
}
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
System.out.println(formattedDate);
}
}
Output : 2014-11-21 You can change the format to any format you want.
If you just want to get the month and day without the seconds, you could call .get(Calendar.MONTH) and .get(Calendar.DATE) and pass them into the constructor of a new date object and return that object.
More info: here
Use this SimpleDateFormat
I didn't test the following code but it will work like:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date myDate = sdf.parse("Fri Nov 21 13:16:57 EST 2014");
I need to add 28 days to a Date - I have tried this:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = df.parse("01/10/2012");
long week = 1000 * 60 * 24 * 7;
date1.setTime(date1.getTime() + week);
but I got an error on this line: Date date1 = df.parse("01/10/2012");
the error: Type mismatch: cannot convert from java.util.Date to java.sql.Date
I also tried this:
Date Mydate = new Date(02,04,2012);
Calendar cal = Calendar.getInstance();
cal.setTime(Mydate);
cal.add(Calendar.DATE, 10); // add 10 days
Mydate = (Date) cal.getTime();
but I got an error when trying to see the Mydate value.
You need to change this line:
import java.sql.Date;
to this:
import java.util.Date;
Once you've done that, I think the best approach is:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 2012);
cal.set(Calendar.MONTH, 3); // NOTE: 0 is January, 1 is February, etc.
cal.set(Calendar.DAY_OF_MONTH, 2);
cal.add(Calendar.DAY_OF_MONTH, 10); // add 10 days
Date date = cal.getTime();
This works for me:
public static void main(String args[]) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
Date date1 = df.parse("01/10/2012");
System.out.println(date1);
Calendar cal = Calendar.getInstance();
cal.setTime(date1);
cal.add(Calendar.DAY_OF_MONTH, 28); // add 28 days
date1 = (Date) cal.getTime();
System.out.println(date1);
}
Try code below:
Calendar MyDate= Calendar.getInstance();
long sum = MyDate.getTimeInMillis() + 2419200000; //28 days in milliseconds
MyDate.setTimeInMillis(sum);
I would like to take a date object like "Sat Feb 17 20:49:54 +0000 2007" and change the year variable to the current year dynamically to something like this "Sat Feb 17 20:49:54 +0000 2012" what would be the best way to do this in java?
Construct a Calendar from the Date, use the Calendar to set the year, and then get back a Date object from the Calendar.
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.YEAR, 2012);
date = c.getTime();
If that's already a date object, you can do this:
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
cal.setTime(dateObj);
//set the year to current year
cal.set(Calendar.YEAR, currentYear);
//new date object with current year
dateObj = cal.getTime();
If that's a string, you can parse the string to a Java Date object first using SimpleDateFormat:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
And the use the above calendar object.
Based on what you asked for, this is how you do that:
try {
DateFormat dateFormat = new SimpleDateFormat("E, dd MMM HH:mm:ss Z yyyy");
date = (Date) dateFormat.parse("Sat, Feb 17 20:49:54 +0000 2007");
Calendar cal = dateFormat.getCalendar();
cal.set(Calendar.YEAR, 2012);
} catch (ParseException pe) {
//ParseException Handling
} catch(Exception e) {
//Exception Handling
}
Another option would be to utilize JodaTime API
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class App
{
public static void main( String[] args )
{
//Sat Feb 17 20:49:54 +0000 2007
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd H:m:s Z yyyy");
DateTime dt = fmt.parseDateTime("Sat Feb 17 20:49:54 +0000 2007");
MutableDateTime mdt = dt.toMutableDateTime();
mdt.setYear(new DateTime().getYear());
System.out.println(fmt.print(mdt));
}
}