How to get the currently time only [duplicate] - java

This question already has answers here:
Change date format in a Java string
(22 answers)
Closed 7 years ago.
Wha would be the equivalent in Java for this C# code:
DateTime.Now.TimeOfDay //This
DateTime.Now.ToString("h:mm:ss tt") //Or This
I'm finding a lot of things, some of them may be deprecated because it has 2 years or more, others are really complex for such a simple thing, and I'm sure there is a simpler way to do so.
I tried:
import java.util.Date;
Date d = new Date();
System.out.println(d); //Result: Wed Oct 28 00:46:29 2015
If I try:
System.out.println(d.getTime()); //Result: 1446000426285
I need to get only time: H:mm:ss

You can use SimpleDateFormat in java. date.getTime() gives you the milliseconds since January 1, 1970, 00:00:00 GMT.
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss");
System.out.println(dateFormat.format(date));

Generally speaking, in Java, date/time objects are just a container for the amount of time which has passed since a given point in time (like the Unix epoch), so they tend not to have there own concept of formatting.
Formatting is normally managed by a supporting API, like java.text.DateFormat or java.time.format.DateTimeFormatter
If you're using Java 8, you could start with LocalTime
LocalTime time = LocalTime.now();
System.out.println(DateTimeFormatter.ISO_LOCAL_TIME.format(time));
which prints 13:51:13.466.
If you need a specific format, you can supply your own pattern to DateTimeFormatter, something like System.out.println(DateTimeFormatter.ofPattern("h:mm:ss a").format(time)); which prints 1:52:31 PM
Have a look at Date and Time Classes for more details

Related

Android timestamp to local user time or date [duplicate]

This question already has answers here:
Unix epoch time to Java Date object
(7 answers)
Closed 5 years ago.
How can I convert minutes from Unix timestamp to date and time in java? For example, timestamp 1372339860 correspond to Thu, 27 Jun 2013 13:31:00 GMT.
I want to convert 1372339860 to 2013-06-27 13:31:00 GMT.
Edit: Actually I want it to be according to US timing GMT-4, so it will be 2013-06-27 09:31:00.
You can use SimlpeDateFormat to format your date like this:
long unixSeconds = 1372339860;
// convert seconds to milliseconds
Date date = new java.util.Date(unixSeconds*1000L);
// the format of your date
SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
// give a timezone reference for formatting (see comment at the bottom)
sdf.setTimeZone(java.util.TimeZone.getTimeZone("GMT-4"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
The pattern that SimpleDateFormat takes if very flexible, you can check in the javadocs all the variations you can use to produce different formatting based on the patterns you write given a specific Date. http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Because a Date provides a getTime() method that returns the milliseconds since EPOC, it is required that you give to SimpleDateFormat a timezone to format the date properly acording to your timezone, otherwise it will use the default timezone of the JVM (which if well configured will anyways be right)
Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
.atZone(ZoneId.of("GMT-4"))
.format(formatter);
System.out.println(formattedDtm); // => '2013-06-27 09:31:00'
I thought this might be useful for people who are using Java 8.
You need to convert it to milliseconds by multiplying the timestamp by 1000:
java.util.Date dateTime=new java.util.Date((long)timeStamp*1000);

Getting 24hr time when adding miliseconds to a Date? [duplicate]

This question already has answers here:
How to add one day to a date? [duplicate]
(18 answers)
Closed 5 years ago.
I have the following Java code that takes a date and should add a full day to the date:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = "2017-01-30T19:00:00+0000"
Date date = formatter.parse(dateString);
long timeBetweenStartDates = 24 * 60 * 1000;
Long DateWithOneDayAddedInMilis = date.getTime()+timeBetweenStartDates;
Date dateWithOneDayAdded = new Date((DateWithOneDayAddedInMilis));
The value I am getting for dateWithOneDayAdded is:
Mon Jan 30 13:24:00 GMT 2017
What I am looking for here would be:
Tue Jan 31 13:24:00 GMT 2017
How can I ensure that the date is in the format I expect?
Oh, what a wonderful example of where the newer date and time classes are much more programmer-friendly. With these it’s next to impossible to make an error like the one you made (and which is pretty easy to make with the old classes, and in particular, very hard to spot once you have written the code).
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ");
String dateString = "2017-01-30T19:00:00+0000";
OffsetDateTime dateTime = OffsetDateTime.parse(dateString, formatter);
OffsetDateTime dateWithOneDayAdded = dateTime.plusDays(1);
System.out.println(dateWithOneDayAdded);
This prints
2017-01-31T19:00Z
You may of course format the calculated date-time the way you or your users prefer.
An added benefit is that plusDays() handles transistion to and from summer time (DST) nicely and hits the same time on the next day (if possible) rather than blindly adding 24 hours.

Java DateFormat for UTC [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 5 years ago.
I have a DateFormat like
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
I have a date like this:
2017-02-23T11:00:04.072625
This "date" is a UTC date (Z is null). This parses fine. However, it seems to be interpreted as the timezone of the machine. So, my machine is EST, this ends up as
2017-02-23T11:00:04.072625-0500
Which is wrong. I can explicitly set the timezone with like
format.setTimeZone(TimeZone.getTimeZone("UTC"));
But if the time came in a different zone in the future, that would not be right either.
If I add a "Z" or "z" to the SimpleDateFormat string, this fails to parse.
Any ideas on how to handle this correctly?
First, since you are using Java 8, start by discarding the old classes Date, DateFormat, SimpleDateFormat and TimeZone. They will more likely than not give you trouble you don’t want. Instead use the classes in java.time introduces in Java 8. Here you go:
String yourDateTime = "2017-02-23T11:00:04.072625";
LocalDateTime ldt = LocalDateTime.parse(yourDateTime);
Instant i = ldt.atOffset(ZoneOffset.UTC).toInstant();
Instant is the new class that best corresponds to the old Date. In this case you get
2017-02-23T11:00:04.072625Z
(Z means UTC)
If in the future you get the date in a different time zone, you may do something like
ZoneId zi = ZoneId.of("Europe/Paris");
Instant i = ldt.atZone(zi).toInstant();
In this case you get instead
2017-02-23T10:00:04.072625Z
Should you for some reason require an oldfashioned Date instance, for example for use with old code, it’s easy:
Date oldfashionedDate = Date.from(i);

how to convert date to millisecond at Java? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
long beginupd = new GregorianCalendar(2014,3,14,10,55,25).getTime().getTime();
Date date = new Date();
long milli=date.getTime();
System.out.println(beginupd);
System.out.println(milli);
System.out.println(date);
output:
1397462125000
1394787327009
Fri Mar 14 10:55:27 EET 2014
What is my wrong? why is it not equal? difference onyl two second but output difference very large
OK!
0 for January and 11 for December. thank you David Wallace
If it is not already a Date, parse it into a Date. The date format is arbitrary as long as you can construct an appropriate SimpleDateFormat to represent it.
After you have a Date, you can use Date.getTime() to retrieve the millisecond value.
For the example you have shown, if you have a string:
String datestr = "2014-14-03 01:39:00";
Then the matching SimpleDateFormat would be:
DateFormat format = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
And conversion would be:
long millis = format.parse(datestr).getTime();
It's no problem to use Date for this, as the constructors and getTime() are still some of the few remaining non-deprecated components.
Edit: I see that you have edited your question to include the use of Date. The constructor you are using is deprecated, and is also not very flexible wrt. input (you have to have the date components already parsed to use it). A SimpleDateFormat provides a non-deprecated way to convert arbitrary strings to dates.
The reason this doesn't work is because the deprecated Date constructor that you're using expects year - 1900 as the first argument.
You should either use a SimpleDateFormat or a GregorianCalendar to do this conversion instead. Since there is already an excellent answer here, showing the use of SimpleDateFormat, here's how you use GregorianCalendar for 1:39am on 14 March 2014.
new GregorianCalendar(2014, 2, 14, 1, 39, 0).getTime().getTime();
Beware that the month uses 0 for January and 11 for December.
There is a nice article on the Date APIs that can be found here.
http://www.mkyong.com/java/java-time-elapsed-in-days-hours-minutes-seconds/
In order to convert to milliseconds, simply do some basic math.

How to convert UTC to PST in java [duplicate]

This question already has answers here:
Convert GMT to IST in java?
(5 answers)
Closed 6 years ago.
I am trying to convert time zone from UTC to GMT in java. I have tried several times and even used your guided method too. I am getting my output with correct timing in GMT format but along with "PDT 2012" written with it. Why so..?? I have tried hundreds of methods but can't get rid of it.
Please help me.
Thanks
For all Date / or DateTime related operations in Java I would recommend to use JodaTime Library
It is very useful to use Date/time with different point of views (calendar, timezone) and for computation as well: adding/substracting months, years, days and so on...
Since Java 8, an equivalent (improvement) of JodaTime is included in the JDK under the new package java.time (JSR-310) and no more needed to add it as dependency.
The author of JodaTime explains in his blog the difference between JodaTime and JSR-310.
Perhaps the following will be a starting point. It converts your current date to GMT:
SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTime());
TimeZone currentTimeZone = cal.getTimeZone();
int offset = currentTimeZone.getOffset(cal.getTimeInMillis());
Date adjustedTime = new Date(cal.getTimeInMillis() - offset);
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormat.format(adjustedTime));
A couple of notes:
You are probably not able see the PST change to UTC because you don't set the timezone on the date format
You shouldn't really use the abbreviations like "GMT" anymore. It is better to use the full name in the id field.
You'll have to be a bit more creative if you happen to run the above code on a system that has its default time already set to GMT.

Categories