How do I get the current time from the internet? - java

This question already has an answer here:
use of ntp service
1 answer
I have browsed the whole site to find a solution. But none of the ones I found worked. And most of them were pretty old. So I want to get the current UTC time from the internet. Completely independent from the phone.
Would be nice if someone could help me.

Just ask google. :)
curl -i google.com | grep Date

I am guessing you meant on coding, if yes these are the ways of getting curent time and date on JAVA:
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class currentTime {
public static void main(String[] args) {
//1
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd
HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
System.out.println(dtf.format(now));
//2
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
System.out.println(formatter.format(date));
//3
System.out.println(java.time.LocalDate.now());
//4
System.out.println(java.time.LocalTime.now());
//5
System.out.println(java.time.LocalDateTime.now());
//6
System.out.println(java.time.Clock.systemUTC().instant());
//7
java.util.Date date1=new java.util.Date();
System.out.println(date1);
//8
long millis=System.currentTimeMillis();
java.util.Date date2=new java.util.Date(millis);
System.out.println(date2);
//9
Date date3=java.util.Calendar.getInstance().getTime();
System.out.println(date3);
}
}

This is a free time service which returns the number of minutes since the Unix epoch:
https://currentmillis.com/time/minutes-since-unix-epoch.php
The Unix epoch is 00:00:00 Thursday, 1 January 1970
Here is some code to fetch this number and create a Calendar object out of it in Java:
URL url = new URL("https://currentmillis.com/time/minutes-since-unix-epoch.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
long minutes = Long.parseLong(in.readLine());
in.close();
con.disconnect();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(minutes * 60000);
System.out.println(minutes);
Note that the time resolution of this service is in minutes, so it will not be accurate to the second, you have to decide whether it's sufficient to your purposes. Also note that if you ship this code it would be nice to make it more robust (e.g. proper exception handling)

Related

Need to get current timestamp in Java

I need to get the current timestamp in Java, with the format of MM/DD/YYYY h:mm:ss AM/PM,
For example: 06/01/2000 10:01:50 AM
I need it to be Threadsafe as well.
Can I utilize something like this?
java.util.Date date = new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
Or the examples discussed at the link here.
The threadunsafety of SimpleDateFormat should not be an issue if you just create it inside the very same method block as you use it. In other words, you are not assigning it as static or instance variable of a class and reusing it in one or more methods which can be invoked by multiple threads. Only this way the threadunsafety of SimpleDateFormat will be exposed. You can however safely reuse the same SimpleDateFormat instance within the very same method block as it would be accessed by the current thread only.
Also, the java.sql.Timestamp class which you're using there should not be abused as it's specific to the JDBC API in order to be able to store or retrieve a TIMESTAMP/DATETIME column type in a SQL database and convert it from/to java.util.Date.
So, this should do:
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 12/01/2011 4:48:16 PM
Print a Timestamp in java, using the java.sql.Timestamp.
import java.sql.Timestamp;
import java.util.Date;
public class GetCurrentTimeStamp {
public static void main( String[] args ){
java.util.Date date= new java.util.Date();
System.out.println(new Timestamp(date.getTime()));
}
}
This prints:
2014-08-07 17:34:16.664
Print a Timestamp in Java using SimpleDateFormat on a one-liner.
import java.util.Date;
import java.text.SimpleDateFormat;
class Runner{
public static void main(String[] args){
System.out.println(
new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new Date()));
}
}
Prints:
08/14/2014 14:10:38
Java date format legend:
G Era designation Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
Try this single line solution :
import java.util.Date;
String timestamp =
new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date());
The fact that SimpleDateFormat is not thread-safe does not mean you cannot use it.
What that only means is that you must not use a single (potentially, but not necessarily static) instance that gets accessed from several threads at once.
Instead, just make sure you create a fresh SimpleDateFormat for each thread. Instances created as local variables inside a method are safe by definition, because they cannot be reached from any concurrent threads.
You might want to take a look at the ThreadLocal class, although I would recommend to just create a new instance wherever you need one. You can, of course, have the format definition defined as a static final String DATE_FORMAT_PATTERN = "..."; somewhere and use that for each new instance.
java.time
As of Java 8+ you can use the java.time package. Specifically, use DateTimeFormatterBuilder and DateTimeFormatter to format the patterns and literals.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendPattern("MM").appendLiteral("/")
.appendPattern("dd").appendLiteral("/")
.appendPattern("yyyy").appendLiteral(" ")
.appendPattern("hh").appendLiteral(":")
.appendPattern("mm").appendLiteral(":")
.appendPattern("ss").appendLiteral(" ")
.appendPattern("a")
.toFormatter();
System.out.println(LocalDateTime.now().format(formatter));
The output ...
06/22/2015 11:59:14 AM
Or if you want different time zone…
// system default
System.out.println(formatter.withZone(ZoneId.systemDefault()).format(Instant.now()));
// Chicago
System.out.println(formatter.withZone(ZoneId.of("America/Chicago")).format(Instant.now()));
// Kathmandu
System.out.println(formatter.withZone(ZoneId.of("Asia/Kathmandu")).format(Instant.now()));
The output ...
06/22/2015 12:38:42 PM
06/22/2015 02:08:42 AM
06/22/2015 12:53:42 PM
You can make use of java.util.Date with direct date string format:
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
Joda-Time
Here is the same kind of code but using the third-party library Joda-Time 2.3.
In real life, I would specify a time zone, as relying on default zone is usually a bad practice. But omitted here for simplicity of example.
org.joda.time.DateTime now = new DateTime();
org.joda.time.format.DateTimeFormatter formatter = DateTimeFormat.forPattern( "MM/dd/yyyy h:mm:ss a" );
String nowAsString = formatter.print( now );
System.out.println( "nowAsString: " + nowAsString );
When run…
nowAsString: 11/28/2013 11:28:15 PM
I did it like this when I wanted a tmiestamp
String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(Calendar.getInstance().getTime());
Hope it helps :) As a newbie I think it's self-explanatory
I think you also need import java.text.SimpleDateFormat; header for it to work :))
String.format("{0:dddd, MMMM d, yyyy hh:mm tt}", dt);
well sometimes this is also useful.
import java.util.Date;
public class DisplayDate {
public static void main(String args[]) {
// Instantiate an object
Date date = new Date();
// display time and date
System.out.println(date.toString());}}
sample output: Mon Jul 03 19:07:15 IST 2017
public class TimeStampExample {
private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss");
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
public static void main(String[] args) {
System.out.println(timestamp);
System.out.println(timestamp.getTime());
Instant instant = timestamp.toInstant();
System.out.println(instant);
System.out.println(instant.toEpochMilli());
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println(timestamp);
Date date = new Date();
System.out.println(new Timestamp(date.getTime()));
System.out.println(timestamp.getTime());
System.out.println(sdf.format(timestamp));
}
}

Java Timestamp Format Conversion

I have a Timestamp format in a string attribute .When I format it is adding some extra minutes i can see deviation in minutes.
Have any one faced.Please help me out here
String dddddd="2017-11-29 09:24:03.857921";
SimpleDateFormat fullMonthFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
SimpleDateFormat fullMonthFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSSSSS");
Date strd11;
strd11=fullMonthFormat1.parse(dddddd);
System.out.println("chec date"+strd11);
String aa=fullMonthFormat2.format(strd11);
System.out.println("aa date"+aa);
o/p
chec dateWed Nov 29 09:38:20 IST 2017
aa date29-Nov-2017 09:38:20.000921
I think the problem are your milliseconds, 857921 milliseconds are equal to ~ 14 minutes (14,2986833), which seems to be the time that got added to your output (output is correct, your input String or pattern needs fixing if you dont want this behaviour)
TestingTest's answers your question already. Yet, if you want a different behaviour which does not re-calculate the minute you could use java.time.LocalDateTime (you need Java 8 though). This class does not mess up the minutes like SimpleDateformat.
See the difference in the code snippet below:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
public class TimeChecks {
public static void main(String[] args) throws ParseException {
String dddddd = "2017-11-29 09:24:03.857921";
SimpleDateFormat fullMonthFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
SimpleDateFormat fullMonthFormat2 = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSSSSS");
Date strd11;
strd11 = fullMonthFormat1.parse(dddddd);
System.out.println("chec date" + strd11);
String aa = fullMonthFormat2.format(strd11);
System.out.println("aa date" + aa);
LocalDateTime localDate = LocalDateTime.parse(dddddd, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"));
System.out.printf("Local date: %s%n", localDate);
}
}
This prints out:
chec dateWed Nov 29 09:38:20 GMT 2017
aa date29-Nov-2017 09:38:20.000921
Local date: 2017-11-29T09:24:03.857921
As you can see local date time does not change the minutes - it keeps the milliseconds as is.

Sum of two hours

I am developing an application where I want to add hours. But I don't know how to do to take into account change of day for example. If I have
9:45 pm + 3:30
it should give
1:15 am
Thanks for help
String time = "2:00 pm";
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
Date date = df.parse(time);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
int h = cal.get(Calendar.HOUR_OF_DAY);
int m = cal.get(Calendar.MINUTE);
It will print 5:30 pm
EDIT: HOUR_OF_DAY provides a 24 h day
import java.util.Calendar;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
class SumHours{
public static void main(String[] args){
DateFormat dateFormat = new SimpleDateFormat("h:mm a");
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,21);
cal.set(Calendar.MINUTE,45);
Date d = cal.getTime();
System.out.println(dateFormat.format(d));
cal.add(Calendar.HOUR, 3);
cal.add(Calendar.MINUTE, 30);
d = cal.getTime();
System.out.println(dateFormat.format(d));
}
}
Output:
9:45 PM
1:15 AM
Since so many have wanted to contribute an answer to this duplicate question (as I regard it), I thought it was time someone contributed the modern answer.
I know you are on Android Java 7, and until Java 8 comes to Android the modern answer requires you to use an external library, the ThreeTenABP. However, not only are the newer Java date and time classes in that library so much nicer to work with, when it comes to time arithmetic this is where they have one of their particularly strong points. So think about it, try it out. It’s also the future since the classes come built-in with Java 8 and later.
DateTimeFormatter timeFormatter
= DateTimeFormatter.ofPattern("h:mm a", Locale.ENGLISH);
LocalTime startTime = LocalTime.of(21, 45);
Duration hoursToAdd = Duration.ofHours(3).plusMinutes(30);
LocalTime resultTime = startTime.plus(hoursToAdd);
System.out.println("" + startTime.format(timeFormatter) + " + " + hoursToAdd
+ " = " + resultTime.format(timeFormatter));
This prints:
9:45 PM + PT3H30M = 1:15 AM
I had wanted to give you lowercase pm and am and 3:30 as in your question. I admit we’re not quite there. In particular PT3H30M is peculiar if you haven’t learned ISO 8601 syntax. It means just 3 hours 30 minutes, easy enough when you know. Duration objects do not lend themselves well to formatting, it will help in Java 9, but as long as Java 8 hasn’t come to Android yet, let’s leave that. If you prefer lowercase pm, you may find the solution in this answer: displaying AM and PM in small letter after date formatting.
My code may not be that much shorter than the code in the other answers, but IMHO it is much easier to read.
Further links
ThreeTenABP
How to use ThreeTenABP in Android Project
Here is one of the decissions when you want to call this in anywhere:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeClass {
static String timeStart24 = "21:45";
static String timeStart = "09:45 PM";
static String timeStep = "3:30";
public String TimeClass(String start, String step) throws ParseException {
// Take hours and minutes apart
String[] time = step.split(":");
// Create format of time
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
SimpleDateFormat df24 = new SimpleDateFormat("HH:mm");
// Input begining time
Date from = df.parse(start);
System.out.println(df.format(from));
System.out.println(df24.format(from) + " - 24 hours format");
// Create calendar instance
Calendar cal = Calendar.getInstance();
cal.setTime(from);
// Inner method add of Calendar
cal.add(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
cal.add(Calendar.MINUTE, Integer.parseInt(time[1]));
System.out.println(df.format(cal.getTime()));
// System.out.print(df24.format(cal.getTime()));
return df.format(cal.getTime());
}
public static void main(String[] args) throws ParseException {
TimeClass tc = new TimeClass();
tc.TimeClass(timeStart, timeStep);
}
}
OUTPUT:
09:45 PM
21:45 - 24 hours format
01:15 AM

Java Computing Time Difference Not Working [closed]

I am trying to compute the difference in time between two date/times. This is what I have imported:
import java.util.concurrent.TimeUnit;
import java.text.*;
import java.util.*;
And this is my code:
SimpleDateFormat format= new SimpleDateFormat("yy/MM/dd HH:mm:ss");
String dateStart = "11/03/14 19:29:58";
String dateStop = "11/05/14 08:03:13";
Date d1=null;
Date d2=null;
try{
d1 = format.parse(dateStart);
d2=format.parse(dateStop);
}
catch(ParseException e)
{
e.printStackTrace();
}
long diff = d2.getTime()-d1.getTime();
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
long minutes=TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println(minutes);
This, I think, should work fine, but instead of the correct answer I get "87153". What is the source of error and how can I correct it?
This seems to be correct.
long seconds = TimeUnit.MILLISECONDS.toSeconds(diff);
System.out.println(seconds);
long minutes=TimeUnit.MILLISECONDS.toMinutes(diff);
System.out.println(minutes);
long hours=TimeUnit.MILLISECONDS.toHours(diff);
System.out.println(hours);
long days=TimeUnit.MILLISECONDS.toDays(diff);
System.out.println(days);
Gives output as
5229195
87153
1452
60
This seems to be correct... You have difference of two months right?
Or else check with your assumption of dates. May be you are making some false assumption with dd and yy, try to put yyyy and inside your year also correct it to 2011 or 2014 as per your expectation. This is my assuption :P
That looks correct to me... you've got just under two months, so 60.5 days (because it starts at ~8pm and ends at ~8am). A day contains 1440 minutes. 1440 * 60.5 is 87120, which is very close to the answer you've received.
It's not clear what answer you expected, but Java's getting the maths right. The source of the error is presumably your expectations :)
(As an aside, you may well want to specify a time zone of UTC unless you want calculations like this to use your local time zone. You could easily get answers which are an hour off your expected results for that reason.)
Always use calendars:
import java.text.SimpleDateFormat;
import java.util.concurrent.TimeUnit;
import java.text.*;
import java.util.*;
public class DateDiff {
public static void main(String[] arg){
SimpleDateFormat format= new SimpleDateFormat("yy/MM/dd HH:mm:ss");
String dateStart = "11/03/14 08:03:58";
String dateStop = "11/05/14 08:20:13";
Date d1=null;
Date d2=null;
try{
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
}
catch(ParseException e)
{
e.printStackTrace();
}
Calendar cal1 = Calendar.getInstance();
cal1.setTime(d1);
Calendar cal2 = Calendar.getInstance();
cal2.setTime(d2);
long seconds = cal2.get(Calendar.SECOND) - cal1.get(Calendar.SECOND);
long minutes= cal2.get(Calendar.MINUTE) - cal1.get(Calendar.MINUTE);
System.out.println(minutes);
System.out.println(seconds);
}
}

Can't get time to calculate based off of UTC

I would expect the code below to render the time correct for me in my local timezone (US EST) but I keep getting the time back 5 hours earlier than my current time. My userTimeZoneOffset value is -300 which is the correct offset minutes from UTC for my timezone. dateAndTimeFormat is set to "MM/dd/yyyy h:mm a" for me.
How can I get the currentDateAndTime variable below to calculate based off of UTC rather than my current timezone?
String dateAndTimeFormat = i18nUtil.getValue(locale, "dateAndTimeFormat");
SimpleDateFormat sdf = new SimpleDateFormat(dateAndTimeFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
if (userTimeZoneOffset != null) {
calendar.add(Calendar.MINUTE, userTimeZoneOffset);
}
String currentDateAndTime = sdf.format(calendar.getTime());
return currentDateAndTime;
As I mentioned in a comment, you should look at Joda-Time instead of the Java DateTime/Calendar library.
To get the current time in UTC, you should import the below packages and call the following line of code:
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
DateTime utcDateTime = new DateTime(DateTimeZone.UTC);
It looks like you also desire subtracting time from the DateTime you receive. For this, you would call the following method:
DateTime estDateTime = utcDateTime.minusHours(5);
Joda-Time: http://www.joda.org/joda-time/

Resources