I am trying to return a validity date, or an expiration date for a file, if you will. Currently, I have a sample program that prints out all the needed information but nnot exactly in the format I get. My code prints out:
Thu May 15 04:57:36 PDT 2014
But I need it to print out like so:
Thu, 15 May 2013 04:57:36 PDT
As you can see, very similar just not quite in the right place. Here is my test code that gives me the first result:
import java.util.Calendar;
import java.util.Date;
public class TestCalendar{
public static void main(String[] args){
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(new Date());
currentDate.add(Calendar.MINUTE, 24);
Date newDate = currentDate.getTime();
System.out.println("Date: " + newDate);
}
}
This code adds 24 minutes to the current time and then prints it out, I just cant figure out how to reformat this date. SimpleDateFormat doesn't seem like it's going to work but I could be wrong. I just couldn't figure it out.
Thanks in advance for any help anyone is able to give me!!
Use SimpleDateFormat:
DateFormat formatter= new SimpleDateFormat("E, d MMM yyyy hh:mm:ss zzz");
Calendar currentDate = Calendar.getInstance();
currentDate.setTime(new Date());
currentDate.add(Calendar.MINUTE, 24);
Date newDate = currentDate.getTime();
System.out.println(formatter.format(newDate));
System.out.println("Date: " + newDate);
invokes toString() on Date instance, which has fixed format, you can't modify that
what you need is to format() your Date instance to String using SimpleDateFormat
Related
Situation: There is an Object AuditLog, which contains the variable java.util.Date date. This Object is saved in a mySQL Database.
#Entity
public class AuditLog implements Persistable<Long> {
...
#Temporal(TemporalType.DATE)
private Date date;
...
}
I am writing some JUnit tests and need to verify that a saved Date equals the actual date. Where date is a local Copy of the value actually passed to the log Object before it got saved and then loaded again.
Assert.assertEquals(date, log.getDate());
Output:
expected:<Wed May 24 15:54:40 CEST 2017> but was:<2017-05-24>
So you can see that the date actually is the right one but only y-m-d
I then tried this (below) to check if the milliseconds get altered.
Assert.assertEquals(date.getTime(), log.getDate().getTime());
Output:
expected:<1495634973799> but was:<1495576800000>
Now i think the best way would be to get the Milliseconds for year month day only.
Question: Can this be achieved relatively simple and should i do this? I think the Date gets altered because of a Database operation of some kind, so adapting the Test is OK right?
There are two ways to do this:
Using local date : You can convert util Date to LocalDate and do assertEquals on both the objects. LocalDate won't have time, e.g.:
Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date);
Using Apache commons' DateUtils: You can use truncate method to set non date fields to zero, e.g.:
Date input = new Date();
Date truncated = DateUtils.truncate(input, Calendar.DATE);
System.out.println(truncated);
Here's the maven dependency for Apache commons library.
You can get the "just the day, month, year by using the following code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Answer {
public static void main(String args[]) throws ParseException {
// parse the date and time
String input = "Wed May 24 15:54:40 CEST 2017";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
// parse just the date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("CEST"));
String formattedDate = formatter.format(date);
Date parsedDate = formatter.parse(formattedDate);
System.out.println(parsedDate);
// use https://currentmillis.com/ to check the milliseconds figures
System.out.println("Wed May 24 15:54:40 CEST 2017 in milliseconds \t" + date.getTime());
System.out.println("Wed May 24 00:00:00 CEST 2017 in milliseconds \t" + parsedDate.getTime());
}
}
The second SimpleDateFormat("yyyy-MM-dd"); parses on the year-month-day.
Use Date.getTime()); to get the milliseconds.
The output is:
Wed May 24 15:54:40 CEST 2017 in milliseconds 1495634080000
Wed May 24 00:00:00 CEST 2017 in milliseconds 1495584000000
1495584000000 = Wed May 24 2017 00:00:00 (using https://currentmillis.com/)
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, 5 - 1);
cal.set(Calendar.DAY_OF_MONTH, 24);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date d = cal.getTime();
System.out.println(d.getTime());
this code creates a new java.util.Date with only year, month and day set. result of this example is 1495576800000 which is what you want.
A shorter way would be this:
Date d = new Date(0l);
d.setYear(117);
d.setMonth(4);
d.setDate(24);
d.setHours(0);
You should format the two dates:
Date date = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
dt.format(date);
Then compare each other.
This question already has answers here:
Java program to get the current date without timestamp
(17 answers)
Closed 6 years ago.
I want to create a Date object without a TimeZone (eg : 2007-06-21). Is this possible?
When I use the following method it prints like Thu Jun 21 00:00:00 GMT 2007
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
TimeZone timeZone = TimeZone.getTimeZone("GMT");
timeZone.setDefault(timeZone);
sdf.setTimeZone(timeZone);
Date pickUpDate = sdf.parse("2007-06-21");
System.out.println(pickUpDate);
If you want to format a date, you need to use DateFormat or something similar. A Date is just an instant in time - the number of milliseconds since the Unix epoch. It doesn't have any idea of time zone, calendar system or format. The toString() method always uses the system local time zone, and always formats it in a default way. From the documentation:
Converts this Date object to a String of the form:
dow mon dd hh:mm:ss zzz yyyy
So it's behaving exactly as documented.
You've already got a DateFormat with the right format, so you just need to call format on it:
System.out.println("pickUpDate" + sdf.format(pickUpDate));
Of course it doesn't make much sense in your sample, given that you've only just parsed it - but presumably you'd normally be passing the date around first.
Note that if this is for interaction with a database, it would be better not to pass it as a string at all. Keep the value in a "native" representation for as much of the time as possible, and use something like PreparedStatement.setDate to pass it to the database.
As an aside, if you can possibly change to use Joda Time or the new date/time API in Java 8 (java.time.*) you'll have a much smoother time of it with anything date/time-related. The Date/Calendar API is truly dreadful.
This is the toString() of the java.util.Date
public String toString() {
// "EEE MMM dd HH:mm:ss zzz yyyy";
BaseCalendar.Date date = normalize();
StringBuilder sb = new StringBuilder(28);
int index = date.getDayOfWeek();
if (index == gcal.SUNDAY) {
index = 8;
}
convertToAbbr(sb, wtb[index]).append(' '); // EEE
convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' '); // MMM
CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd
CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':'); // HH
CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
TimeZone zi = date.getZone();
if (zi != null) {
sb.append(zi.getDisplayName(date.isDaylightTime(), zi.SHORT, Locale.US)); // zzz
} else {
sb.append("GMT");
}
sb.append(' ').append(date.getYear()); // yyyy
return sb.toString();
}
So, if you will pass a Date and try to print it this will be printed out all the time.
Code:
Date date = new Date();
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(date));
Date : Fri Apr 29 04:53:16 GMT 2016
Sample Output : 2016-04-29
Imports required :
import java.util.Date; //for new Date()
import java.text.SimpleDateFormat; // for the format change
System.out.println("pickUpDate " + sdf.format(pickUpDate));
You can use the above code to get formatted Date as String
Use this Code:
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date pickUpDate =sdf.parse("2007-06-21");
System.out.println("pickUpDate "+sdf.format(pickUpDate));
Hope it'll help you.
String your_format_date=sdf.format(pickUpDate);
System.out.println("pick Up Date " + your_format_date);
Date isn't a date. It's a timestamp. That's some impressive API design, isn't it?
The type you need is now java.time.LocalDate, added in Java 8.
If you can't use Java 8, you can use ThreeTen, a backport for Java 7.
This is both a duplicate and not a duplicate!
Just please help me and don't refer me to anywhere else, cause I'm really unable to get the GMT time.
The answer seems easy but it doesn't work for me.
I don't know are the answers all aver the web wrong, or am I making a mistake?
Please take a look at this snippet and the results:
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long time = cal.getTimeInMillis();
Date date = new Date(time);
System.out.println(date);
time = System.currentTimeMillis();
date = new Date(time);
System.out.println("--\n" + date);
result :
Fri Feb 28 16:07:12 GMT+03:30 2014--
Fri Feb 28 16:07:12 GMT+03:30 2014
Both show my local time. I even printed directly the time, cause I thought maybe this is due to Date class but even those are the same (with just about 1 or 2 milliseconds difference).
Use setTimeZone() on a SimpleDateFormat to print the date in a specific timezone.
DateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss z");
Date d = format.parse("28-Feb-2014 13:00:00 PST");
System.out.println(format.format(d));
format.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(format.format(d));
Prints:
28-Feb-2014 13:00:00 PST
28-Feb-2014 21:00:00 GMT
Try the below
SimpleDateFormat f = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
f.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(f.format(new Date(System.currentTimeMillis())));
One way of doing it is using SimpleDateFormat and the setTimeZone method():
SimpleDateFormat sdf = new SimpleDateFormat( "..." );
sdf.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); // or UTC
System.out.println( sdf.format( date ) );
Cheers,
I would like the time respresented as this "Thu Jan 01 08:40:38 GMT+01:00 1754"
so i did this :
Date datu = new Date();
datu.setYear(1754);
datu.setMonth(0);
datu.setDate(1);
DateFormat.format("%tc", datu);
// DATU = Thu Jan 01 08:40:38 GMT+01:00 3654
String startTime = datu.toGMTString();
now the problem is that i set the year on 1754 in the code. but as I print it out. there is 3654 ?
EDIT:
datu.setYear(1754-1900) can do the trick. but isn't there another way?
Please try like this :
SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd hh:mm:ss 'GMT'Z yyyy");
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR,1754);
c.set(Calendar.MONTH, 0); // JAN
c.set(Calendar.DATE, 1);
System.out.println(sdf.format(new Date(c.getTimeInMillis())));
Output
Tue Jan 01 05:23:55 GMT+0800 1754
What version of the Java API are you using?
I would suggest you use the java.text.SimpleDateFormat and java.util.Calendar instead.
You code would look something like this:
Calendar cal = Calendar.getInstance();
cal.set(1754, 0, 1);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // <- customize your format
sdf.format(cal.getTime()); // <- get your string
The date.toGMTString() method is also deprecated so it's best to avoid it.
It seems that date.SetYear is deprecated. According to the documentation you should use Calendar.set(Calendar.YEAR, year) instead.
As you said, date.setYear(desired year-1900) fixes the problem. It is noteworthy that the method is deprecated it is better you use the Calendar class which doesnt require subtracting 1900 from the year. A code snippet that will achieve what you are doing using Calendar is giving below:
Calendar calendar =Calendar.getInstance();
calendar.setTime(date);// note that the date object here will be datu according to
//your code. It could be any object of the Date class
int year = calendar.get(Calendar.YEAR);
Hope this helps.
Feel free to mark as answer if it solves your problem.
Good luck!
I am having following function
public static Date parseDate(String date, String format) throws ParseException
{
SimpleDateFormat formatter = new SimpleDateFormat(format);
return formatter.parse(date);
}
I am using this as follows in my code
Calendar eDate = Calendar.getInstance();
eDate.add(Calendar.DAY_OF_MONTH,10);
Date date = null;
try {
date = parseDate(eDate.getTime().toString(),"yyyy-MM-dd hh-mm-ss");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But it is throwing -
java.text.ParseException: Unparseable date
What is the problem here?
The format is not stored in the Date. It is stored in the String. The Date#toString() returns a fixed format which is described in its Javadoc.
Do the formatting only at the moment you need to display a Date to a human as a String.
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH, 10);
Date date = calendar.getTime();
String formattedDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
System.out.println(formattedDate);
Note that MM stands for months and mm for minutes. See also SimpleDateFormat javadoc.
You'll be happy to hear that there's never a need to parse a date from a Calendar object: The way to pull a Date out of a Calendar is via the getTime() method.
EDIT:
To output the date in eDate in ISO style format:
final DateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
String formattedDate = isoFormat.format(eDate.getTime());
That's untested, but I think it should work.
You're currently formatting with the default format from java.util.Date, and then parsing with a potentially different format. You should also change your format string - it's currently using a 12 hour clock with no am/pm indicator, and minutes twice. I think you mean: "yyyy-MM-dd HH-mm-ss"
Don't use toString() for anything like that. toString() should be used only for debug messages.
Use DateFormat.format(..) to produce a string in a predictable form.
You're inserting a Zulu Timestamp (UNIX), getTime() returns the number of milliseconds since January 1, 1970, 00:00:00 GMT. Then you define the format as yyyy-mm-dd hh-mm-ss and try to parse the timestamp with this pattern. Which doesn't match.
You could use Date date = calendar.getTime(); and then format it via new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(date);
you can simply use the date returned by the calendar, instead of transforming it into string and back into a date (apparently using a wrong date format). The date can be obtained by:
eDate.getTime()
There seems to be no need for SimpleDateFormat in your case.
Check the Date.toString() method.
The api states that it returns it in
the format:
dow mon dd hh:mm:ss zzz yyyy
which is:
Mon Jan 28 14:22:07 EST 2004
You are telling the parser to expect: 2004-01-28 14-22-07
eDate.getTime().toString()
returns a String representation of a date in this format:
dow mon dd hh:mm:ss zzz yyyy (see the java.util.Date API).
You are trying to parse a date using this format:
yyyy-mm-dd hh-mm-ss .
The code is correctly throwing the ParseException.