import java.util.*;
import java.text.*;
public class GetPreviousAndNextDate
{
public static void main(String[] args)
{
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
String prevDate = dateFormat.format(date.getTime() - MILLIS_IN_DAY);
String currDate = dateFormat.format(date.getTime());
String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY);
System.out.println("Previous date: " + prevDate);
System.out.println("Currnent date: " + currDate);
System.out.println("Next date: " + nextDate);
}
}
i have this error
(Error(9,32): method format(long) not found in class java.text.SimpleDateFormat )
Your code's logic is wrong. The results will be an hour off around the Daylight Savings Time switch, because that involves days that are 23 or 25 hours long.
For date arithmethic, you should always use the Calendar class:
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
String prevDate = dateFormat.format(cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 2);
String nextDate = dateFormat.format(cal.getTime());
(note that Calendar.getTime() returns a Date object and thereby fixes the type error as well)
In order to create a date from a long you simply have to use the new Date(long) API:
new Date(date.getTime() - MILLIS_IN_DAY);
These lines use a method which doesn't exist:
String prevDate = dateFormat.format(date.getTime() - MILLIS_IN_DAY);
String currDate = dateFormat.format(date.getTime());
String nextDate = dateFormat.format(date.getTime() + MILLIS_IN_DAY);
Method format accepts Date objects as parameters.
Try this:
String prevDate = dateFormat.format(new Date(date.getTime() - MILLIS_IN_DAY));
Related
If the user selects 01:25 AM, how to get the corresponding epoch time for this hour for the next day?
I did something like that, which is pretty "face coded" :
private long returnEpochForThisHour(String hour){
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
Date date = new Date();
String stringDate = dateFormat.format(date).substring(0, 10) + " " + hour;
Date newDate = new Date(stringDate);
Calendar c = Calendar.getInstance();
c.setTime(newDate);
c.add(Calendar.DATE, 1);
Date lastDate = c.getTime();
System.out.println(lastDate.getTime());
return lastDate.getTime();
}
When doing something like:
returnEpochForThisTime("01:25");
It returns:
1544491500000
But in Android devices it's not working properly. Is there a better way to do this?
I have a Date object in Java stored as Java's Date type.
I also have a Gregorian Calendar created date. The gregorian calendar date has no parameters and therefore is an instance of today's date (and time?).
With the java date, I want to be able to get the year, month, day, hour, minute, and seconds from the java date type and compare the the gregoriancalendar date.
I saw that at the moment the Java date is stored as a long and the only methods available seem to just write the long as a formatted date string. Is there a way to access Year, month, day, etc?
I saw that the getYear(), getMonth(), etc. methods for Date class have been deprecated. I was wondering what's the best practice to use the Java Date instance I have with the GregorianCalendar date.
My end goal is to do a date calculation so that I can check that the Java date is within so many hours, minutes etc of today's date and time.
I'm still a newbie to Java and am getting a bit puzzled by this.
Use something like:
Date date; // your date
// Choose time zone in which you want to interpret your Date
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris"));
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
// etc.
Beware, months start at 0, not 1.
Edit: Since Java 8 it's better to use java.time.LocalDate rather than java.util.Calendar. See this answer for how to do it.
With Java 8 and later, you can convert the Date object to a LocalDate object and then easily get the year, month and day.
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int day = localDate.getDayOfMonth();
Note that getMonthValue() returns an int value from 1 to 12.
Date date = new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE");
System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("MMMM");
System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase());
simpleDateFormat = new SimpleDateFormat("YYYY");
System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase());
EDIT: The output for date = Fri Jun 15 09:20:21 CEST 2018 is:
DAY FRIDAY
MONTH JUNE
YEAR 2018
You could do something like this, it will explain how the Date class works.
String currentDateString = "02/27/2012 17:00:00";
SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date currentDate = sd.parse(currentDateString);
String yourDateString = "02/28/2012 15:00:00";
SimpleDateFormat yourDateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date yourDate = yourDateFormat.parse(yourDateString);
if (yourDate.after(currentDate)) {
System.out.println("After");
} else if(yourDate.equals(currentDate)) {
System.out.println("Same");
} else {
System.out.println("Before");
}
private boolean isSameDay(Date date1, Date date2) {
Calendar calendar1 = Calendar.getInstance();
calendar1.setTime(date1);
Calendar calendar2 = Calendar.getInstance();
calendar2.setTime(date2);
boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
return (sameDay && sameMonth && sameYear);
}
It might be easier
Date date1 = new Date("31-May-2017");
OR
java.sql.Date date1 = new java.sql.Date((new Date()).getTime());
SimpleDateFormat formatNowDay = new SimpleDateFormat("dd");
SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM");
SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY");
String currentDay = formatNowDay.format(date1);
String currentMonth = formatNowMonth.format(date1);
String currentYear = formatNowYear.format(date1);
Date queueDate = new SimpleDateFormat("yyyy-MM-dd").parse(inputDtStr);
Calendar queueDateCal = Calendar.getInstance();
queueDateCal.setTime(queueDate);
if(queueDateCal.get(Calendar.DAY_OF_YEAR)==Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
{
"same day of the year!";
}
#Test
public void testDate() throws ParseException {
long start = System.currentTimeMillis();
long round = 100000l;
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay(new Date());
}
long mid = System.currentTimeMillis();
for (int i = 0; i < round; i++) {
StringUtil.getYearMonthDay2(new Date());
}
long end = System.currentTimeMillis();
System.out.println(mid - start);
System.out.println(end - mid);
}
public static Date getYearMonthDay(Date date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd");
String dateStr = f.format(date);
return f.parse(dateStr);
}
public static Date getYearMonthDay2(Date date) throws ParseException {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.HOUR_OF_DAY, 0);
return c.getTime();
}
public static int compare(Date today, Date future, Date past) {
Date today1 = StringUtil.getYearMonthDay2(today);
Date future1 = StringUtil.getYearMonthDay2(future);
Date past1 = StringUtil.getYearMonthDay2(past);
return today.compare // or today.after or today.before
}
getYearMonthDay2(the calendar solution) is ten times faster. Now you have yyyy MM dd 00 00 00, and then compare using date.compare
I am trying to display Date based on timezone.
If I change my system time zone to US pacific time zone, today's date is displayed correctly. If I want to display 2000-01-01 output shows as 12/31/1969.
Can you please let me know if I have to make any change in system settings or java settings?.
Below is the example code:
package timezoneexample;
import java.text.DateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimezoneExample {
public static void main(String args[]) {
DateFormat dateFormat = null;
String datePattern = null;
char dateSeperator = '/';
try {
datePattern = "MM/dd/yyyy";
if (datePattern.length() <= 0)
throw new java.util.MissingResourceException(
"Didn't find date format", "", "");
boolean hasSeperatorAlready = false;
for (int i = 0; i < datePattern.length(); i++)
if (!Character.isLetter(datePattern.charAt(i)))
if (hasSeperatorAlready)
throw new java.util.MissingResourceException(
"Unvalid date format", "", "");
else
dateSeperator = datePattern.charAt(i);
} catch (java.util.MissingResourceException mre) {
System.out.println(mre);
}
dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM);
if (datePattern.length() > 0
&& dateFormat instanceof java.text.SimpleDateFormat) {
java.text.SimpleDateFormat sdf = (java.text.SimpleDateFormat) dateFormat;
sdf.applyPattern(datePattern);
}
dateFormat.setTimeZone(java.util.TimeZone.getDefault());
// enter DOB
Date dob = new Date(2000 - 01 - 01);
Date today = new Date();
String timeZone = System.getProperties().getProperty("user.timezone");
TimeZone tZone = TimeZone.getTimeZone(timeZone);
System.out.println("Timezone : " + tZone);
dateFormat.setTimeZone(tZone);
System.out.println("Date Of Birth : " + dateFormat.format(dob));
System.out.println("Date in Displayed as per Timezone : "
+ dateFormat.format(today));
}
}
Output:
Timezone : sun.util.calendar.ZoneInfo[id="America/Los_Angeles",offset=-28800000,dstSavings=3600000,useDaylight=true,transitions=185,lastRule=java.util.SimpleTimeZone[id=America/Los_Angeles,offset=-28800000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=3,startMonth=2,startDay=8,startDayOfWeek=1,startTime=7200000,startTimeMode=0,endMode=3,endMonth=10,endDay=1,endDayOfWeek=1,endTime=7200000,endTimeMode=0]]
Date Of Birth : 12/31/1969
Date in Displayed as per Timezone : 01/07/2015
Your error is here:
Date dob = new Date(2000 - 01 - 01);
This will be interpreted as:
Date dob = new Date(1998);
This will invoke the Date(long date) constructor, resulting in a date near 1970/01/01.
What you most probably want is:
Date dob = new Date(2000, 1, 1);
new Date(...) requires a long value, expressing the number of milliseconds since 1/1/1970. You're specifying 2000 - 1 - 1. This is NOT "year 2000, month 1 and day 1", it is a numeric expression equal to 1998 milliseconds.
To create a date based on year/month/day, use a Calendar:
Calendar c = Calendar.getInstance();
c.set(y, m-1 /* 0-based */, d); // e.g. c.set(2000, 0, 1);
return c.getTime();
This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 8 years ago.
I have a object that giving date and time in this format "2014-06-11 16:32:36.828".
I want to remove millisec .828.
In my db that object is in time stamp format but whenever i am showing i am converting it to tostring().
so how to remove millisec please help me
The following code convert "2014-06-11 16:32:36.828" into "2014-06-11 16:32:36"
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828"));
Explanation:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse("2014-06-11 16:32:36.828") parse the input string into
Wed Jun 11 16:32:36 IST 2014
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) format the input date into specified structure.
I would use DateUtils.truncate(date, Calendar.SECOND)
Date d = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(yourString);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
I remember there is a way to directly read Date off your timestamp field but I don't do that in my everyday coding. So I'd left for others to post so. Nevertheless, you can use the same above code to translate your date from that timestamp into a date without MILLISECOND.
If you receive it as a Timestamp, you should use the appropriate formatter when converting it to a string:
String s = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(timestamp);
Note: this will use the default time zone of the local computer.
Extract epoch millis from the original Date object and do integer division by 1000 followed by multiplication by 1000. Create Date object with the time zone of the original object and the millis calculated the above suggested way.
You can get the system time as follows without milliseconds
import java.text.SimpleDateFormat;
import java.util.Calendar;
And the code
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter= new SimpleDateFormat("dd-MM-YYYY-hh:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
System.out.println(dateNow);
if you want to mantain the format try something like that:
public static String getFechaTimestampToString (Timestamp timestamp) {
String date = "";
Calendar cal = Calendar.getInstance();
cal.setTime(new Date(timestamp.getTime()));
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int day = cal.get(Calendar.DAY_OF_MONTH);
String monthstr = "";
String daystr = "";
if(month<10)
monthstr = "0"+month;
else
monthstr = ""+month;
if(day<10)
daystr = "0"+day;
else
daystr = ""+day;
date = year + "-" + monthstr + "-" + daystr ;
return date;
}
To reverse data to database:
public static Timestamp getFechaStringToTimestamp (String strDate) {
Timestamp timestamp = null;
strDate = strDate + " 00:00:00";
timestamp = Timestamp.valueOf(strDate);
return timestamp;
}
Why is getTime() having an error? I have tried everything, but cannot figure out what the problem is. As far as I know, I have converted the String arrayOpportunity[2] into a date. (It was originally a String.) Thanks!
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("yyyy-MM-dd HH:mm:ss");
// Calendar timestamp = Calendar.getInstance();
// timestamp.setTime(df.parse(arrayOpportunity2)[0]);
arraySuspects.add(arrayGPS[0]);
// }
// long timediff = coord2.getTimestamp().getTimeInMillis() -
// coord1.getTimestamp().getTimeInMilis();
Date convertedDate = df.parse(arrayOpportunity[2]);
Date duration = df.parse("0000-00-00 00:14:59");
Date lastTime = df.parse(arrayOpportunity[2]);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/mm/dd");
System.out.println(arrayOpportunity[2]);
// arrayOpportunity[2].setTime(arrayOpportunity[2].getTime() + duration);
// lastTime += duration;
arrayOpportunity[2].setTime(arrayOpportunity[2].getTime() + (((14 * 60) + 59)* 1000));
Calling df.parse(arrayOpportunity[2]); does not convert arrayOpportunity[2] to a Date, it assigns that value to lastTime. In your code call lastTime.getTime() instead of arrayOpportunity[2].getTime() as arrayOpportunity[2] is still a String
// Create your date parser
SimpleDateFormat df = new SimpleDateFormat();
// Set the date pattern
df.applyPattern("yyyy-MM-dd HH:mm:ss");
// Create a Date object by parsing the value of arrayOpportunity[2]
Date lastTime = df.parse(arrayOpportunity[2]);
// Set a new value to the Date object by performing a calculation on the result of getTime()
lastTime.setTime(lastTime.getTime() + (((14 * 60) + 59)* 1000));