This question already has answers here:
How can I increment a date by one day in Java?
(32 answers)
Closed 8 years ago.
Sorry im new to java, may i know how can i add extra time in here?
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(new Date());
System.err.println("currTimestamp=="+currTimestamp); // 2014/10/17 14:31:33
You can use Calender for this.
Calendar calendar=Calendar.getInstance(); // current time
System.out.println(calendar.getTime());
calendar.add(Calendar.MINUTE,3); // add 3 minutes to current time
System.out.println(calendar.getTime());
Out put:
Fri Oct 17 12:17:13 IST 2014
Fri Oct 17 12:20:13 IST 2014
Just as a comparison, using Java 8's new time API...
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
ldt = ldt.plusMinutes(3);
System.out.println(ldt.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)));
Or if you can't use Java 8, you could use the JodaTime API
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dt = DateTime.now();
System.out.println(timestampFormat.format(dt.toDate()));
dt = dt.plusMinutes(3);
Date date = dt.toDate();
System.out.println(timestampFormat.format(dt.toDate()));
Calander class have some useful methods to do this. If you want to still use Date it self, Add 3000 milliseconds to the current time.
String resultTime = timestampFormat.format(new Date(new Date().getTime() + 3000));
It would be better to use the Calendar class instead of using deprecated Date class:
Pull a Calendar instance:
Calendar c = Calendar.getInstance();
Add 3 minutes to the calendar current time:
c.add(Calendar.MINUTE, 3);
Format the new calendar time:
SimpleDateFormat timestampFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String currTimestamp = timestampFormat.format(c.getTime());
System.err.println("currTimestamp==" + currTimestamp);
Related
I am facing issue like I have a datasheet which have a string value like 123459 which is a time and I have another column where I am adding in value as plus 5 seconds.
When I am adding value its add as 123464 instead of 123504.
Could anyone help me to resolve this?
Use the java.time classes built into Java 8 and later. See Oracle Tutorial.
Specifically, the LocalTime and DateTimeFormatter classes.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHmmss");
LocalTime localTime = LocalTime.parse("123459", formatter);
LocalTime timeIn5Seconds = localTime.plusSeconds(5);
System.out.println(timeIn5Seconds.format(formatter));
Output
123504
to convert string to date format...
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = (Date)formatter.parse(str);
to add 5 seconds
Calendar cal = Calendar.getInstance(); // creates calendar
cal.setTime(date); // sets calendar time/date according to the OBJECT
cal.add(Calendar.SECOND, 5); // adds 5 SECONDS
cal.getTime();
This question already has answers here:
Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time
(7 answers)
Closed 8 years ago.
I'm trying to get an instance of Date with UTC time using the following code:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date now = cal.getTime();
that looks so simple, but if I check the values at IntelliJ's debugger, I get different dates for cal and now:
cal:java.util.GregorianCalendar[time=1405690214219,areFieldsSet=true,lenient=true,zone=GMT,firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_YEAR=29,WEEK_OF_MONTH=3,DAY_OF_MONTH=18,DAY_OF_YEAR=199,DAY_OF_WEEK=6,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=1,HOUR_OF_DAY=13,MINUTE=30,SECOND=14,MILLISECOND=219,ZONE_OFFSET=0,DST_OFFSET=0]
now:Fri Jul 18 10:30:14 BRT 2014
as you can see, cal is 3 hours ahead of now... what am I doing wrong?
Thanks in advance.
[EDIT] Looks like TimeZone.setDefault(TimeZone.getTimeZone("UTC")); before the code above does the job...
This question has already been answered here
The System.out.println(cal_Two.getTime()) invocation returns a Date from getTime(). It is the Date which is getting converted to a string for println, and that conversion will use the default IST timezone in your case.
You'll need to explicitly use DateFormat.setTimeZone() to print the Date in the desired timezone.
TimeZone timeZone = TimeZone.getTimeZone("UTC");
Calendar calendar = Calendar.getInstance(timeZone);
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("EE MMM dd HH:mm:ss zzz yyyy", Locale.US);
simpleDateFormat.setTimeZone(timeZone);
System.out.println("Time zone: " + timeZone.getID());
System.out.println("default time zone: " + TimeZone.getDefault().getID());
System.out.println();
System.out.println("UTC: " + simpleDateFormat.format(calendar.getTime()));
System.out.println("Default: " + calendar.getTime());
Edit To convert cal to date
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
System.out.println(year);
Date date = new Date(year - 1900, month, day); // is same as date = new Date();
Just build the Date object using the Cal values. Please let me know if that helps.
Try using a date formatter and set the time zone to UTC.
dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
This question already has answers here:
Modify the week in a Calendar
(4 answers)
Closed 5 years ago.
I am getting a Date from the object at the point of instantiation, and for the sake of outputting I need to add 2 weeks to that date. I am wondering how I would go about adding to it and also whether or not my syntax is correct currently.
Current Java:
private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private Date dateOfOrder;
private void setDateOfOrder()
{
//Get current date time with Date()
dateOfOrder = new Date();
}
public Date getDateOfOrder()
{
return dateOfOrder;
}
Is this syntax correct? Also, I want to make a getter that returns an estimated shipping date, which is 14 days after the date of order, I'm not sure how to add and subtract from the current date.
Use Calendar and set the current time then user the add method of the calendar
try this:
int noOfDays = 14; //i.e two weeks
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOfOrder);
calendar.add(Calendar.DAY_OF_YEAR, noOfDays);
Date date = calendar.getTime();
I will show you how we can do it in Java 8. Here you go:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 2 week to the current date
LocalDate next2Week = today.plus(2, ChronoUnit.WEEKS);
System.out.println("Next week: " + next2Week);
}
}
The output:
Current date: 2016-08-15
Next week: 2016-08-29
Java 8 rocks !!
Use Calendar
Date date = ...
Calendar c = Calendar.getInstance();
c.setTime(date);
c.add(Calendar.WEEK_OF_MONTH, 2);
date = c.getTime();
Try this to add two weeks.
long date = System.currentTimeMillis() + 14 * 24 * 3600 * 1000;
Date newDate = new Date(date);
if pass 14 to this addDate method it will add 14 to the current date and return
public String addDate(int days) throws Exception {
final DateFormat dateFormat1 = new SimpleDateFormat(
"yyyy/MM/dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.setTime(new Date()); // Now use today date.
c.add(Calendar.DATE, addDays); // Adding 5 days
return dateFormat1.format(c.getTime());
}
Using the Joda-Time library will be easier and will handle Daylight Saving Time, other anomalies, and time zones.
java.util.Date date = new DateTime( DateTimeZone.forID( "America/Denver" ) ).plusWeeks( 2 ).withTimeAtStartOfDay().toDate();
If you are on java 8 you can use new date time api http://docs.oracle.com/javase/8/docs/api/java/time/LocalDateTime.html#plusWeeks-long-
if you are on java 7 or more old version of java you should use old api http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#add-int-int-
This question already has answers here:
Is java.util.Date using TimeZone?
(5 answers)
Closed 7 years ago.
String = 26/8/2013 15:59;
I want to convert this date into GMT, however after applying the below code, I get the EEST time rather than the GMT.
DateFormat df = new SimpleDateFormat("dd/MM/yyyy h:m");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
df.parse(newDate);
Log.i(tag, df.parse(newDate).toString());
Output :
Mon Aug 26 18:59:00 EEST 2013
Whats wrong ?
Your parsing is correct, the different is just for your locale time zone that is used to display when you are making toString(). I just used formatted output to demonstrate the correct format . Here is the details example:
final String time = "26/8/2013 15:59";
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(time);
// localDate.toString()
// PRINT. Mon Aug 26 15:59:00 EEST 2013
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
// PRINT. 26/08/2013 12:59
Nothing's really wrong. You are successfully parsing the datetime string interpreted as UTC timezone.
When printing it to log, you get what you ask for - Date.toString() returns the date formatted to current locale settings which include the timezone. The difference between UTC and EEST is 3 hours.
If you want to to format it to display some other timezone, pass it though format() of a SimpleDateFormat that is configured to the timezone you want.
I think you should use the below approach:
Date myDate = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTime(myDate);
Date time = calendar.getTime();
SimpleDateFormat outputFmt = new SimpleDateFormat("MMM dd, yyy h:mm a zz");
String dateAsString = outputFmt.format(time);
System.out.println(dateAsString);
Ok so I am trying to create a date in this format:
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yy");
I am having trouble calculating that date so that it gives me 1/1/13.
Date newdate = new Date (136199001);
String date = dateformat.format(newdate);
However I can't work out how to do it to get to my desired date. I know I am suppose to work it out from 01/01/70 but I am having trouble. The question : what is the formula to work the date out?
I would say that what you are looking for is this:
new SimpleDateFormat("dd/MM/yy").parse("1/1/13");
You can use calendar object for a specific date. It is much easier.
Calendar cal = Calendar.getInstance();
cal.set(2013, 0, 1); //1st january 2013
Date date = cal.getTime();
SimpleDateFormat dateformat = new SimpleDateFormat("dd-MM-yy");
String dateStr = dateformat.format(date);