I just need a small help regarding the DateTime format in java.I am writing a simple chat application based on yahoo messanger,in which I will read the packet of yahoo messanger and display the chat messages.Now I want to display the time from the given header.In a particular article it is said the "timestamp" will be 0x477BBA61(decimal 1199290977) which means "Wed, 2 Jan 2008 16:22:57 GMT" .
I am trying to reveal how that decimal is converted to that particular date.I tried to write a simple java application to convert that and its giving some other time.
public static void main(String[] arg)
{
Calendar obj = Calendar.getInstance();
obj.setTimeZone(TimeZone.getTimeZone("GMT"));
obj.setTimeInMillis(1199290977l);
System.out.println( obj.get(Calendar.HOUR)+":"+obj.get(Calendar.MINUTE));
}
output:9:8
Can anybody help me with this?
Your value of 1199290977L is wrong. That's measuring in seconds since the Unix epoch (midnight on January 1st 1970 UTC) - you need to multiply it by 1000 to get milliseconds since the epoch.
You're also using Calendar.HOUR which is the 12-hour clock instead of Calendar.HOUR_OF_DAY which is the 24-hour clock. This code:
Calendar obj = Calendar.getInstance();
obj.setTimeZone(TimeZone.getTimeZone("GMT"));
obj.setTimeInMillis(1199290977000L);
System.out.println(obj.get(Calendar.HOUR_OF_DAY) + ":" +
obj.get(Calendar.MINUTE));
... prints 16:22.
However, you should definitely use the java.text.DateTimeFormat class instead of doing this yourself - or, ideally, use Joda Time instead.
Imho to proceed you need to know:
whether or not that number is milliseconds or not
what is the starting point (in java is January 1, 1970, 00:00:00 GMT)
The timezone is probably in seconds; try to multiply the value by 1000 to get the milliseconds which Calendar expects.
You need to use a SimpleDateFormat - look at the documentation, it is pretty easy to understand, plus it includes a lot of examples (so you don't need to search for "date format tutorial" or something like that :))
EDIT: Ooops, I missed the part where you are passing the time in seconds instead of milliseconds and the result time is wrong, I misinterpreted your question and thought that you want to just parse the time, Jon's answer is better :)
Related
I have a time in milliseconds: 1618274313.
When I convert it to time using this website: https://www.epochconverter.com/, I am getting 6:08:33 AM.
But when I use SimpleDateFormat, I am getting something different:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313)));
I am getting output as 23:01:14.
What is the issue in my code?
In your example, you are using time 1618274313 and you are assuming that it is in milliseconds. However, when I entered the same time on https://www.epochconverter.com/, I got below results:
Please notice the site mentions: Assuming that this timestamp is in seconds.
Now if we use that number multiplied by 1000 (1618274313000) as the input so that the site considers it in milliseconds, we get below results:
Please notice the site now mentions: Assuming that this timestamp is in milliseconds.
Now, when you will use 1618274313000 (correct time in milliseconds) in Java with SimpleDateFormat, you should get your expected result (instead of 23:01:14):
SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss", Locale.getDefault());
System.out.println(sdf.format(new Date(1618274313000)));
use Instant.ofEpochSecond
long test_timestamp = 1618274313L;
LocalDateTime triggerTime =
LocalDateTime.ofInstant(Instant.ofEpochSecond(test_timestamp),
TimeZone.getDefault().toZoneId());
System.out.println(triggerTime);
it prints output as 2021-04-13T06:08:33
Assuming it is in milliseconds as you say, all you know for certain is that you have a specific duration.
Duration d = Duration.ofMillis(1618274313);
System.out.println(d);
Prints
PT449H31M14.313S
Which says it is 449 hours, 31 minutes and 14.313 seconds of duration. Without knowing the epoch of this duration and any applicable zone offsets, it is not really possible to ascertain the specific date/time it represents. I could make lots of assumptions and provide results based on that, but more information from you would be helpful.
java.time
As Viral Lalakia already spotted, the epoch converter that you linked to, explicitly said that it assumed that the number was seconds (not milliseconds) since the epoch. The following makes the same assumption in Java. I recommend that you use java.time, the modern Java date and time API.
ZoneId zone = ZoneId.of("Asia/Kolkata");
long unixTimestamp = 1_618_274_313;
Instant when = Instant.ofEpochSecond(unixTimestamp);
ZonedDateTime dateTime = when.atZone(zone);
System.out.println(dateTime);
System.out.println(dateTime.format(DateTimeFormatter.ISO_LOCAL_TIME));
Output is:
2021-04-13T06:08:33+05:30[Asia/Kolkata]
06:08:33
This agrees with the 6:08:33 AM that you got from the converter. And the date is today’s date. A coincidence?
If the number is indeed milliseconds (which I honestly doubt), just use Instant.ofEpochMill() instead of Instant.ofEpochSecond().
Instant when = Instant.ofEpochMilli(unixTimestamp);
1970-01-19T23:01:14.313+05:30[Asia/Kolkata]
23:01:14.313
This in turn agrees with the result you got in Java (except that the milliseconds are also printed).
I want to convert this java code to C# code
Can any one help me please ? thanks in advance
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal=Calendar.getInstance(TimeZone.getDefault());
Date dateGMT= cal.getTime();
I'm that expert with c# (had some background with it though..), but you may try this code if you want to get the current utc time:
DateTime dt= DateTime.UtcNow;//get the UTC/GMT time now...
//different time formats...
dt.ToString("HH:mm"); // 07:00 // 24 hour clock // hour is
//always 2 digits
dt.ToString("hh:mm tt"); // 07:00 AM // 12 hour clock // //hour
//is always 2 digits
dt.ToString("H:mm"); // 7:00 // 24 hour clock
dt.ToString("h:mm tt"); // 7:00 AM // 12 hour clock
Console.Write(dt); //print result or you can do something about the result..
I have tried to write the different format then print it. I hope I have helped you. Don't hesitate to comment if you have further questions
DateTime.UtcNow is one way.
Luckily .UtcNow (Coordinated Universal Time) is always GMT (excepting leap-seconds).
C# has an absolutely gigantic library. The best place to start is its documentation.
I'm looking to convert a Joda LocalDate to unix epoch time (long) in Java.
I've looked in to the LocalDate documentation and there doesn't appear to be anything on getting this value.
Link
I'm new to Joda and have been searching around and haven't found a right way of doing this yet. I know this has to be easy but I haven't figured it out. Any help would be appreciated.
In a general case it's not as simple as it seems - Unix time defines a continuous timeline starting at 1970-01-01 00:00 UTC. LocalDate is - as the name suggests - local to a certain place in the world. The beginning and end of the day 2015-01-01 is at a different point in time in Sydney than in Berlin. Also, Unix time involves time whereas LocalDate... not ;) So - if it indeed makes sense to convert a Local Date to a UTC timestamp there are two questions you must answer for yourself:
in which time zone do you want to interpret the LocalDate?
what should be the time part after the conversion?
Assuming it does make sense to do it and you can answer the questions, you can implement it using
LocalDate#toDateTime(LocalTime time, DateTimeZone zone)#getMillis()
or - if you want the start of the day
LocalDate#toDateTimeAtStartOfDay(DateTimeZone zone)#getMillis()
I'm making a basic Java program that reads in a subtitle (.srt) file and I would like to store each time as a Date object. I really only need to keep track of Hours, minutes, seconds, and milliseconds (to 3 digits). I think I am able to store it using this:
String start = "00:01:01,604";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss,SSS");
Date startDate = sdf.parse(start);
For retrieving, I can do something like this:
return String.format("\nStart: %d:%d:%dText: %s\n", startDate.getHours(),startDate.getMinutes(), startDate.getSeconds(), text);
I'm looking for something that would do something similar to getMilliseconds (if it existed). Thank you very much!
What you're handling is not a date! Don't use the Date class to handle it! Dates have strange extra rules that you don't care about and that could easily trip you up (just think of leap years, leap seconds and time zones).
You should either
use a long to hold the milliseconds and handle the calculation on your own (it's not so hard, you're not implementing a calendar) or
use an existing duration class such as the one from Joda Time.
The recommended way to get access to part of date (hours,minutes, etc.) in Java is now using Calendar.get(Calendar.MILISECONDS), see javadocs. In case of your code it would look like this:
Date startDate = sdf.parse(start);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
int milliseconds = calendar.get(Calendar.MILISECONDS);
P.S. Please note that regarding to javadocs Date.getHours(),Date.getSeconds(), etc. methods are currently deprecated anyway. Don't use them :).
Just call date.getTime() and get milliseconds.
You can always use Date.getTime() for getting value in milliseconds. It will return a value in long format
Given a any unix timestamp (i.e. 1306396801) which translates to 26.05.2011 08:00:01, how can I determine if this is within a given timeframe (i.e. 08:00:00 and 16:00:00)?
This needs to work for any day. I just want to know if this timestamp is within the given time-interval, on any future (or past) day, the date is unimportant. I don't care if it is on the 25th or 26th, as long as it is between 08:00 and 16:00.
I am on the lookout for a java solution, but any pseudo code that works will be ok, I'll just convert it.
My attempts so far has been converting it to a java Calendar, and reading out the hour/min/sec values and comparing those, but that just opened up a big can of worms. If the time interval I want it between is 16.30, I can't just check for tsHour > frameStartHour && tsMin > frameStartMin as this will discard any timestamps that got a minute part > 30.
Thank you for looking at this :)
To clarify.
I am only using and referring to UTC time, my timestamp is in UTC, and the range I want it within is in UTC.
I think I understand what you want. You want to test for any day, if it's between 8am and 4pm UTC. Take the timestamp mod 24*3600. This will give you the number of seconds elapsed in the day. Then you just compare that it's between 8*3600 and 16*3600. If you need to deal with timezones, things get more complicated.
Given your timestamp (in seconds) and the desired time zone, Jodatime gives you the hour which leads you to a simple integer range check.
new org.joda.time.DateTime(timestamp*1000L, zone).getHourOfDay()
With java.util.* its more difficult.
If I understood you correctly, you only need to normalize your dates to some common value. Create three instances of Calendar - one with your time, but day, month, and year set to zero, and two with start and end of your timeframe, other fields also zeroed. Then you can use Calendar.after() and Calendar.before() to see if the date is within the range.
Your unix timestamp is an absolute time. Your time frame is relative. You need some kind of time zone information in order to solve this problem. I just answered some of this for PostgreSQL a few minutes ago. Hopefully that article is of use.
Convert the beginning of your range to a unix timestamp, and the end of your range to a unix tmestamp, then it's a simple integer check.