Getting the exact time and date for my log track - java

Good day Lovely people
Please help a brother out. Well I'm a master in visual basic but in java let me rather not say.
In VB here are my methods:
System.DateTime.Now.ToLongTimeString()
System.DateTime.Now.ToString() + "/" + System.DateTime.Now.Month.ToString() + "/" + System.DateTime.Now.Year.ToString()
The first method will return the exact time e.g = 12:08:36 AM
And the second method will return the exact date e.g = 2012/09/26
I want to get the very same results but using java.How do i go about doing that.
Oooh Thanks in advance.

In .NET, DateTime.Now gives you the local date and time, in your local time zone.
If you use new Date() or the like in Java, it will give you a value which has no awareness of time zones. To take time zones into account, you should either create a Calendar which has the right time zone, or if you want to create an appropriate string you should use SimpleDateFormat - again, set to the right time zone before formatting. For example:
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
format.setTimeZone(...); // Whichever time zone you want
String text = format.format(new Date()); // "now"
Also note that Joda Time is a much better Java API for date/time than the built-in Calendar and Date classes.
Finally, your second piece of sample code in .NET is buggy - you should only evaluate DateTime.Now once; ideally just passing in a format string e.g. DateTime.Now.ToString("yyyy/MM/dd"). Even if you want to convert each bit to a string separately, however, you fetch the value once to a local variable and then reuse it. Otherwise, if you execute that code around midnight, the date can change - so for example, if you executed it just before the start of 2013, you could end up with a string of "2012/12/1" or "2012/1/1" neither of which would be correct.

Use java.text.SimpleDateFormat class to format date and new java.util.Date() will create an instance system date default.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat dateFormat1 = new SimpleDateFormat("hh:mm:ss a");
System.out.println(dateFormat.format(new Date)); //2012/09/26
System.out.println(dateFormat1.format(new Date)); //12:08:36 AM

To get the object representing the current date, you can use just new Date(), to format it, use SimpleDateFormat.

Related

Why UTC timezone giving ahead time for System.currentTimeMillis in Java?

I am getting current time from Ruby on Rails webservice in Unix Timestamp format (ie. in seconds from 1 Jan 1970), the timezone on server is UTC.
In Java I am trying to convert local current time to UTC time. But every time it is giving 6+ minutes ahead time. I want to get the difference of UTC current time and the time returned from service. My Java code is -
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
Date utc_current = new Date(System.currentTimeMillis());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
long serverTime = 1424936268000L;
long resTime = sdf.getCalendar().getTimeInMillis() - serverTime;
System.out.println("Time Diff : " + resTime);
Where serverTime is the time I am getting from webservice. And the value for resTime shows negative value which is approx 6+ minutes.
So my question is why UTC timezone giving ahead time for System.currentTimeMillis?
In contrast to the assumption in a comment of of #JB Nizet the expressions sdf.getCalendar().getTimeInMillis() and System.currentTimeMillis() are not equivalent. Proof:
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println("date via System.currentTimeMillis()=" + f.format(utc_current));
System.out.println("date via sdf.getCalendar()=" + f.format(new Date(resTime)));
Output:
date via System.currentTimeMillis()=2015-02-26T12:19:09
date via sdf.getCalendar()=1889-12-31T04:41:21
If you carefully study the source code of SimpleDateFormat and DateFormat you will find within the initialization part code like:
private void initializeDefaultCentury() {
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add( Calendar.YEAR, -80 );
parseAmbiguousDatesAsAfter(calendar.getTime());
}
The conclusion is to strictly avoid the method getCalendar() on your DateFormat-object. It is only used as intermediate mutable object for internal format and parse processing. It is hard to say what you will really get as time this way. Instead use directly System.currentTimeMillis() to compare your local time with server time.
Another problem is the pattern you use. "dd-MM-yyyy hh:mm:ss" is probably not correct because it uses the clock hour of half day in range 1-12 but the information for am/pm is missing. Use better the pattern symbol HH. Check the documentation of webservice for the right format.
Make sure the the clock on the server and on the client machine are synchronized. The 6 minutes could simply be an offset between the two.

How to getDate with yyyy-MM-dd format

How can I get the current date of the system with this format yyyy-MM-dd
I want this
SimpleDateFormat formatDate = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String strDate = formatDate.format(now);
return strDate;
but returning a Date instead of a String.
Any help is greatly appreciated.
UPDATE: If that's the case, can I parse my String to Date?
How can i get the current date of the system with this format yyyy-MM-dd but returns Date instead of String.
You can't. There's no such thing as "a Date with a format" any more than there's the concept of "an int with a format". A Date value is just a point in time, with no associated text format, calendar system or time zone.
Using new Date() will get you a Date object representing the current instant in time, and nothing else. How you use that is up to you - but if you return it from a method then there is no associated date (as the date will vary by time zone), no format etc - it's up to the calling code to use it appropriately.
You might want to consider using Joda Time which at least has a LocalDate type - although you still need to consider which time zone you want to use when you think about "the current date". (And there's still no formatting information associated with the value.)
EDIT: To answer your update, you can just use SimpleDateFormat to parse - but it's not clear where your string has come from to start with. This sounds like the opposite requirement from the rest of your question.
since you cant change Date format build your own CustomDate, it is just a representation of time.
on the method which recieves the date as a string
use another simpledateformatter
and convert the string into date by using
simpledateformatter.parse(strDate);
You can use this .!!
String formatDate = new SimpleDateFormat("yyyy-MM-dd").format( yourDate);

Formatting a Calendar object and not a Date object?

I am trying to format a calendar string to indicate a time zone offset other than my local one. I am aware I could create a simple formatting string and use the Calendar.get(int) method to fill in all the values, but this does not feel like the right way to do this.
Java has a DateFormat, specifically I am trying to use the SimpleDateFormat. The problem is that the format() method of these classes expects a Date object.
I am primarily working with Calendar objects since I believe those are the recommended structure in Java. So, when I go to format my result time, I call Calendar.getTime() which returns a Date object which can be passed into the SimpleDateFormat object.
Until now, I thought this was perfectly simple, but here is where the problem comes in.
Whenever one calls the Calendar.getTime() method, the Date returned is always in the local time zone, regardless of the time zone of the Calendar.
So, I always get the time printed in the local time zone when I pass it to my SimpleDateFormat, which is not what I want. All the research I have done so far says it can't be done and all the examples I have seen simply use the Calendar.get(int) method to fill in some blanks. This seems terrible, why have a DateFormat class if it is going to be so useless?
Here is some example code so you can see what I mean, paste this into your favourite test class:
private static final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
public static void main(String[] args)
{
try
{
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
cal.setTimeInMillis(parser.parse("2012-10-09T22:01:49.108-0700").getTime());
System.out.println(formatter.format(cal.getTime()));
}
catch(ParseException e)
{
e.printStackTrace();
}
}
Output produced (because I am running in Central Time Zone): 2012-10-10T00:01:49-0500
Output expected (should not matter what time zone it is run from): 2012-10-10T01:01:49-0400
To summarize question: Is there a way to make the DateFormat in java accept a Calendar, or a way to get a Date that is not in the local timezone, or is there another class I should be using altogether for this formatting?
Whenever one calls the Calendar.getTime() method, the Date returned is always in the local time zone, regardless of the time zone of the Calendar.
No, it's not. Date doesn't have a time zone. It's just the number of milliseconds since the Unix epoch. Its toString() method does convert it to the local time zone, but that's not part of the information in the Date object.
All you need to do is set the time zone of the formatter to be the same as the time zone of the calendar.
formatter.setTimeZone(calendar.getTimeZone());
... or just set the calendar to be used entirely:
formatter.setCalendar(calendar);
(It's not immediately clear to me whether the latter approach will mean that the calendar can lose its value... basically the Java classes mix "calendar system", "time zone" and "value within the calendar" in a single type, which is very unfortunate.)
I agree with Ian though, in terms of Joda Time being a far more pleasant API to use.
I would give up on the built in java date and time classes for this and use joda time instead. It is designed to handle ISO8601 format strings properly and does the right thing with timezones.
Date is not having any TimeZone, its just the number of milliseconds since Epoch time, represented in a human readable format. We can use "DateFormat" class.
TimeZone tz = TimeZone.getTimeZone("America/Buenos_Aires");
Calendar cal = Calendar.getInstance(tz);
Date d = cal.getTime();
DateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm aaa");
df.setTimeZone(tz);
String s = df.format(cal.getTime());
System.out.println(s);

Java (Processing Environment) will not provide me with the local time

I'm trying to get the epoc time adjusted for the local timezone (i.e. GMT-7, but it displays GMT). I'm fairly sure this should work, but it's not...
Calendar localTime = new GregorianCalendar(TimeZone.getDefault());
Date dd = localTime.getTime();
long t = dd.getTime()/1000;
System.out.printf("%d\n",t);
But it still outputs the epoc time based on GMT, not GMT-7 (my timezone). After playing around for some time I did get this to work...
Date ddd = new Date();
long t = ddd.getTime() + TimeZone.getDefault().getOffset( ddd.getTime() );
t = t/1000;
But why isn't the first block working?
A Date object simply wraps the UTC time in milliseconds since the epoch. This is how all time is represented 'under the hood' in Java. This also makes it consistent to work with. Whenever you want to print something out, apply the TimeZone offset and DST offset to it.
This is why the SimpleDateFormat class accepts a TimeZone but there is no TimeZone setter on the Date class.
Obligatory: I have heard Joda Time is a much easier to use datetime API.
Also, have a look at this post on the standard date and time libraries in Java.

how to deal with international time?

i build a new website.but the host is in USA.i am not in USA.
i need get the time on the website page to compare with one local Variable.
But because of time difference,it has 8 hous difference。how to solve this problom?
my code
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
java.util.Date currentTime = new java.util.Date();
String dateString = formatter.format(currentTime); `
how to revise these code ?
java.util.Date does not support timezones. You should pass the TimeZone to the formatter instead, by calling formatter.setTimeZone(tz).
joda-time is considered a better choice when working with dates. Note that for the sake of formatting it is fine to use Date, but it is a general advise not to rely on it when it comes to i18n. (Note the many deprecated methods there)
Then make each user set his timezone. Ideally suggest / assume the timezone based on his browser locale. See here
And always store the dates in a fixed timezone - preferably GMT/UTC.
In order to handle timezones, Java includes the Olson timezone database. Find the city in the database that is in the same time zone as you are.
First, you need to get a TimeZone object for the timezone you want. Then, get a Calendar object with the current date and time (or the date and time you wish to use). You can format that with a SimpleDateFormat object.
TimeZone local = TimeZone.getTimeZone("Asia/Tokyo");
Calendar now = Calendar.getInstance(local); // gets time in the current timezone
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
formatter.setTimeZone(local)
String dateString = formatter.format(now.getTime());
Though if you're doing a lot of time manipulation, like Bozho says, go for joda-time. The Java date/time system is confusing and rather poorly designed.
In such cases I always change timezone in Linux:
mv /etc/localtime /etc/localtime-backup
ln -sf /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime
It also can be helpful for reading log files for example (I always see my local time instead of calculating it each time when I need to dig into them)
I think you need to use a Calendar (they are more useful generally than just Date objects). If you create a Calendar, initialised with your locale and timezone, you can do calendar.setDate() using the date you created. If you create another Calendar object with the fields that were entered, you can then do comparisons between the two Calendar objects.

Categories

Resources