I'm parsing the times from AD. There are two formats, i.e., YMD LDAP timestamps for whenCreated, whenChanged, 18-digit LDAP/FILETIME timestamps for lastLogonTimestamp, pwdLastSet, etc. Because I need to analyze the data upon the time. It makes sense to get local time. Here are the two functions that I wrote to parse the two different formats. The calculation in the second function I referenced from Convert 18-digit LDAP Timestamps To Human Teadable Date Using Java
public static String parseLdapDate(String ldapDate) {
String[] parts = ldapDate.split("[.]");
String dateTimePart = parts[0]; //take the date string before .0Z
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT")); //Z means UTC time, to the local timezone
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
Date tempDate = sdf.parse(dateTimePart); //parse the string to a date
return formatter.format(tempDate); //format it as what we want
} catch (ParseException ex) {
System.out.println("Parsing LDAP Date exception \n");
ex.printStackTrace();
}
return null;
}
public static String parseLdapTimestamp(String ldapTimestamp) {
long nanoseconds = Long.parseLong(ldapTimestamp); // 100 nanoseconds
long mills = (nanoseconds/10000000); // To seconds
long unix = (((1970-1601)*365)-3+Math.round((1970-1601)/4))*86400L;
long timeStamp = mills - unix;
Date date = new Date(timeStamp*1000L); // To milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
return sdf.format(date);
}
I have an example 20150520143936.0Z, which is converted to "2015-05-20 16:39:36".
For the example 131097986571852097, it is converted to "2016-06-07 18:44:17", while http://www.epochconverter.com/ldap tells me that it's the GMT time and the local time is "2016-06-07 20:44:17". I will get the local time if I comment the code of setting timezone.
So now I'm confused, sdf.setTimeZone(TimeZone.getTimeZone("GMT")); gives me local timezone or the universal time. I was thinking if AD stores whenCreated in the universal time, lastLogonTimestamp in local time. But in the functions I parse them as strings. There is no symbol about the timezone. If I comment this sentence in the second function, will I get local time for both attributes when I access an LDAP Directory in another place.
In the second case, you're constructing a Date and then telling it to format that date in UTC - whereas in the first case, you're parsing it in UTC, but formatting it in local time. You're already assuming that the timestamp is stored as a number of ticks since the Unix epoch, which is a time zone neutral format.
If the aim is to produce a string representation in local time, then you should remove the sdf.setTimeZone call. I would argue that a parse method should be returning a Date anyway though, rather than a String. Or better yet, return a java.time.Instant...
Related
I'm trying to do a very simple task.
Convert a time (long myTime) in epoch seconds, to a String (but without any adjustment).
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Instant AA = Instant.ofEpochSecond(myTime);
String reportDate = df.format(Date.from(AA));
The "reportDate" is automatically adjusted with GMT offset of Windows.
I need instead the exact instant to string conversion.
I'm new on Java ....
Set the time zone specifically
df.setTimeZone(TimeZone.getTimeZone("GMT"));
This sets the offset to whatever you need so it will output the same date time on any server.
I m facing a problem:I want to get current time of GMT TimeZone in long.
I m using the following code as given below:
TimeZone timeZoneGmt = TimeZone.getTimeZone("GMT");
long gmtCurrentTime = getCurrentTimeInSpecificTimeZone(timeZoneGmt);
public static long getCurrentTimeInSpecificTimeZone(TimeZone timeZone) {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(timeZone);
long finalValue = 0;
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd yyyy hh:mm:ss:SSSaaa");
sdf.setTimeZone(timeZone);
Date finalDate = null;
String date = sdf.format(cal.getTime());
try {
finalDate = sdf.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finalValue = finalDate.getTime();
return finalValue;
}
As given in, above method
while formatting
String date = sdf.format(cal.getTime());
I m getting correct current time in GMT but as i do parsing by following code:
finalDate=sdf.parse(date);
Date got changed from current GMT time to 15:35:16 IST 2013 that is current time of my system.
I tried with Calendar as well in another way:
TimeZone timeZoneGmt=TimeZone.get("GMT");
Calendar calGmt = Calendar.getInstance();
calGmt.setTimeZone(timeZoneGmt);
long finalGmtValue = 0;
finalGmtValue = calGmt.getTimeInMillis();
System.out.println("Date......" + calGmt.getTime());
but still getting date as current time of my System Thu Jan 23 15:58:16 IST 2014 Not getting GMT current time.
You've misunderstood how Date works. A Date doesn't have a time zone - if you use Date.toString() you'll always see the default time zone. The long value in a Date is purely the number of milliseconds since the Unix epoch: it doesn't have any concept of time zone or calendar system.
If you want to represent a date and time in a particular time zone and calendar, use Calendar instead - but for getting "the current date and time as a long" you can just use System.currentTimeMillis(), which again does not have anything to do with the system time zone.
Additionally, even if you did want to do manipulation like this, you shouldn't be using string conversions. You're not conceptually performing any string conversions, so why introduce them?
If your aim is to display (as a string) the current date and time in a particular time zone, you should just use something like:
Date date = new Date(); // This will use the current time
SimpleDateFormat format = new SimpleDateFormat(...); // Pattern and locale
format.setTimeZone(zone); // The zone you want to display in
String formattedText = format.format(date);
When working with date and time APIs - particularly bad ones like the Java Calendar/Date API - it's very important that you understand exactly what each value in your system represents.
I used jflow-0.3[1] to collect and decode netflow records which I receive from a router.
nettrack.net.netflow.Flow.java class contains the code for decoding necessary data from records received. I called getFirst() function of it which returns "The time in Coordinated Universal Time (UTC) seconds when this data collection period began."[2]. Then I converted it into date time format using following code.
long seconds = getFirst();
long millis = seconds * 1000;
Date date = new Date(millis);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE,MMMM d,yyyy h:mm,a", Locale.ENGLISH);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
But when I run this I observe weird results for date like Monday,March 2,1970 4:21,PM, Sunday,April 27,2059 4:17,AM,etc. UTC value is also change from very small values like 300 to very large values like 3154137089 which does not make any sense. What is the problem here? how can I solve this?
https://github.com/aptivate/netgraph/tree/master/jflow-0.3
http://www.cisco.com/en/US/docs/net_mgmt/netflow_collection_engine/6.0/tier_one/user/guide/data.html
I have a date that I get from a server formatted in EST like this
05/07/2012 16:55:55 goes month/day/year then time
if the phone is not in EST how can I convert it to the timezone the phone is in?
it would be not problem if I got the time in milliseconds but I dont
EDIT:
ok now the time is not correct when formatting
String sTOC = oNewSTMsg.getAttribute("TOC").toString();
String timezoneID = TimeZone.getDefault().getID();
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("EST"));
String newtimezoneID = TimeZone.getDefault().getID();
Date timestamp = null;
try{
timestamp = format.parse(sTOC);
format.setTimeZone(TimeZone.getDefault());
timezoneID = format.format(timestamp);
}catch(ParseException e){
}
I convert it to "EST" then format that time to the default TimeZone but the time is always off by an hour, not sure why?
Use the following code to get a UNIX timestamp:
String serverResp = "05/07/2012 16:55:55";
DateFormat format = new SimpleDateFormat("MM/dd/yy HH:mm:ss");
Date date = format.parse(serverResp);
Now you have the timestamp, which you know how to use.
Here's another question which covers conversion, in case you are curious: Android Convert Central Time to Local Time
Use the DateFormat class to parse the String into a Date. See the introduction to the API document here... http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DateFormat.html
You can then create a Calendar for the Date...
Calendar cal = Calendar.getInstance().setTime(date);
And then you can change the timezone on the Calendar to a different timezone using setTimezone(). Or just get the time in milliseconds, using getTimeInMillis()
Using the Calendar, Date, and DateFormat classes should put you in the right direction.
See the Calendar documentation here... http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Calendar.html
I have a MySql database that stores a timestamp for each record I insert. I pull that timestamp into my Android application as a string. My database is located on a server that has a TimeZone of CST. I want to convert that CST timestamp to the Android device's local time.
Can someone help with this?
Use getTimeZone.getDefault combined with according to the Android documentation.
public static synchronized TimeZone
getDefault ()
Gets the default time zone. Returns
the default time zone.
So since you know that CST is -6:00 from GMT, and you get a local timezone saying the user is +9:00 (Japan), you'd know to adjust your MySQL DB times by +15 hours (9 - (-6)). Or if they are in Miami (EST, -5), you would adjust by adding one hour (-5 - (-6)). If the are in Portland, Oregon, (PST -8), you would subtract 2 hours (-8 -(-6)).
So really you just need to get the local timezone offset and feed it into the basic equation: TimeZone.getDefault + 6 and you'll know what to add or subtract to your local DB. (+6 since -(-6) always works out to +6).
If I knew the first thing about writing Java, I'd go the extra step and write a bit of sample code, but alas, I'm only smart enough for scripts.
Crude Attempt at Java
I already said I have no idea how to do Java or object oriented anything, right?
Here's a crude attempt from just poking around the Android documentation. Any fine points or simple "Not even close" remarks welcome. Bear in mind that I figured out the right method and class already just from a quick search and I came up with a simple equation for converting the timezone offset for anywhere to CST, so I'm not a dunce, just someone who doesn't know when to leave well enough alone. Anyway, crude attempt:
System now = System.currentTimeMillis (); //Gets current local time in ms
TimeZone local_tz = TimeZone.getDefault(); //Gets current local TZ of phone
tz_offset_gmt = local_tz.getOffset(now)/3600000; // Get Offset in ms, divide by 3600000
tz_offset_cst = tz_offset_gmt + 6; // add offset to 6 to get current TZ offset to CST.
Anywhere close to how to do this in java?
Suppose you have a string of date in CST, parse it with timezone CST and then format it with the default timezone on your android.
String s = "2011-01-01 12:00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("CST"));
Date timestamp = null;
try {
timestamp = df.parse(s);
df.setTimeZone(TimeZone.getDefault());
System.out.println(df.format(timestamp));
} catch (ParseException e) {
e.printStackTrace();
}
can't you simply convert the date with simpleDateFormat?
then you just define the structure of your incoming date like that (df) and transform it to the form you want (df):
private static DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
private static DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy 'at' HH:mm");
public void setyourDate(String yourDate) {
Date date2;
yourDate = getyourDate() + "" + yourDate;
try {
date2 = df.parse(yourDate);
yourDate = df2.format(date2);
} catch (ParseException e) {
}
this.yourDate = yourDate;
}
does it make sense?
This is an old question, but I want to write my answer. Assume, the timestamp you get from SQL is like the following format: yyyy-MM-dd'T'HH:mm:ss
public static Date convertStringToDate(String strDate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("CST"));
return sdf.parse(strDate);
}