how to parse this date - java

I cant quite figure out what the format should be to parse this date. Its a millisecond value followed by timezone. thx.
// so far tried: "S Z"
// "SSSSSSSSSSS-ZZZZ",
// "SSSSSSSSSSS-Z",
// etc.
Format formatter = new SimpleDateFormat("SSSSSSSSSSSS Z", Locale.CANADA);
// source string looks like this /Date(928164000000-0400)/
String temp = jsonUserObj.getString("DateOfBirth").substring(6, 6+17);
System.err.println("got date="+temp);
Date date = (Date) formatter.parseObject(temp);

You can do it without parser.
String[] parts = new String[]{temp.substring(0, temp.indexOf('-')), temp.substring(temp.indexOf('-') + 1)};
long millis = Long.parseLong(parts[0]);
parts[1] = parts[1].replaceAll("^0*(\\-?[0-9]*)$", "$1");
int timeZone = Integer.parseInt(parts[1]);
int rawOffset = (timeZone / 100) * 3600000 + (timeZone % 100);
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeInMillis(millis);
cal.setTimeZone(new SimpleTimeZone(rawOffset, "GMT"));

SimpleDateFormat expects a milliseconds value < 1000, as it expects you would increment seconds, then minutes, etc, for larger values.
You'll need to convert the value first; this post might help: Unix epoch time to Java Date object

Related

Converting a string to date format when the String ends in Z

I have to parse the following String into a more readable date format.
String date = "20190112151605.0Z";
However, I've never encountered the Z before. I know it has to do with the time zone but when I try to use my usual code I get a java.lang.NumberFormatException.
My code is as follows:
String whenChanged = "20190112151605.0Z";
long DIFF_NET_JAVA_FOR_DATE_AND_TIMES = 11644473600000L;
long adDate1 = Long.parseLong(whenChanged);
long adLongDate1 = ( adDate1 / 10000 ) - DIFF_NET_JAVA_FOR_DATE_AND_TIMES;
Date lastLogonDate1 = new Date(adLongDate1);
String format2 = new SimpleDateFormat("MM/dd/yyyy
HH:mma'Z'").format(lastLogonDate1);
Any help would be great. Thanks
This will do the trick. The Z means UTC time zone
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMddHHmmss.Sz");
ZonedDateTime parsed = ZonedDateTime.parse("20190112151605.0Z", fmt);
System.out.println(parsed); // prints 2019-01-12T15:16:05
See DateTimeFormatter
Is it necessary for you to do anything with these time zones?
If not you could do
if(whenChanged.contains('Z')){
whenChanged = whenChanged.substring(0,date.indexOf('Z'));
}

Java Subtract 2 duration in HH:MM:SS

I have 2 string in java (HH:MM:SS) please take note this is not time, but duration, i used end time - start time to get these values:
Case1:
duration1 = "12:04:45";
duration2 = "13:04:45";
Expected result: duration1 - duration 2 = "-1:00:00" (Note that there is negative)
Case2:
duration1 = "15:13:32";
duration2 = "12:04:45";
Expected result: duration1 - duration 2 = "3:08:47"
How can i do that? My attempt for the Case1 (codes modified from Java add dates of format dd:HH:mm:ss):
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String s1 = "12:04:45";
String s2 = "13:04:45";
Date d1 = format.parse(s1);
Date d2 = format.parse(s2);
int sec = d1.getSeconds() - d2.getSeconds();
int min = d1.getMinutes() - d2.getMinutes();
int hr = d1.getHours() - d2.getHours();
Time sum = new Time(hr, min, sec);
System.out.println(sum); // Output: 23:00:00 which is wrong
Using LocalTime or date calculations like some people suggest doesn't work if your period involved more than 24 hours since that doesn't fit in a day.
If you don't have Java 8, you can use JodaTime. I've just checked that this code also works with JodaTime 1.6.2, which is the last version that still works with JDK 1.4.2.
PeriodFormatter formatter = new PeriodFormatterBuilder()
.printZeroAlways().minimumPrintedDigits(2)
.appendHours().appendSuffix(":").appendMinutes().appendSuffix(":").appendSeconds()
.toFormatter();
Period period1 = formatter.parsePeriod("12:04:45");
Period period2 = formatter.parsePeriod("13:04:45");
Period difference1 = period1.minus(period2).normalizedStandard();
System.out.println(formatter.print(difference1));
Period period3 = formatter.parsePeriod("15:13:32");
Period period4 = formatter.parsePeriod("12:04:45");
Period difference2 = period3.minus(period4).normalizedStandard();
System.out.println(formatter.print(difference2));
Output:
-01:00:00
03:08:47
JodaTime:
Version 1.6.2 source: https://github.com/JodaOrg/joda-time/releases/tag/v1.6.2
Version 1.6.2 Maven Jar artifact: http://mvnrepository.com/artifact/joda-time/joda-time/1.6.2
With the Java time API you could use a Duration to calculate the duration and format it as you want:
String s1 = "12:04:45";
String s2 = "13:04:45";
LocalTime t1 = LocalTime.parse(s1);
LocalTime t2 = LocalTime.parse(s2);
Duration d = Duration.between(t2, t1);
System.out.println(d); //PT-1H
If you want to print it as -1:00:00 you will need to tweak the output format. It could look like this:
private static String toHHMMSS(Duration d) {
long hours = d.toHours();
int minutes = (int) (d.toMinutes() % 60);
int secs = (int) (d.getSeconds() % 60);
return hours + ":" + minutes + ":" + secs;
}
Use Calendar to calculate the time difference.
You can query each field and/or format as a time string as this example shows:
private Calendar getTimeDiffDate(Date d1, Date d2) {
Calendar c = Calendar.getInstance();
c.setTime(new Date(d1.getTime()-d2.getTime()));
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
// Format as a time string:
String formattedTime = formatter.format(c.getTime());
System.out.println("formattedTime: "+formattedTime);
// Query by each field:
System.out.println("Hours: "+c.get(Calendar.HOUR));
System.out.println("Minutes: "+c.get(Calendar.MINUTE));
System.out.println("Seconds: "+c.get(Calendar.SECOND));
return c;
}

Bigquery.jobs().query returns epoch time 1.295353708E9 for timestamp column

Bigquery.jobs().query().execute returns epoch time for timestamp and that epoch time includes dot with trailing alphanumeric value(1.295353708E9) thus converting that value to a Java timestamp fails;
Object v = checkNullAndGetColumnValue(columnIndex);
long epoch = Long.parseLong(v.toString());
String date = new java.text.SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(new java.util.Date (epoch*1000));
the returned value 1.295353708E9 is the same as 1295353708 however not sure what the best way to handle that as bq web UI renders it.
Any help highly appreciated!
I do this way
Calendar cal = Calendar.getInstance();
double d = Double.parseDouble("1.295353708E9");
long l = (long) d * 1000;
cal.setTimeInMillis(l);
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(cal
.getTime());
Anyway, i think bigquery timestamp format is "YYYY-MM-dd HH:mm:ss.SSS"
This should work:
long epoch = Double.valueOf("1.295353708E9").longValue();
String date = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss")
.format(new Date (epoch*1000));
With the given example value, the date string resolves to 01/18/2011 21:28:28.

How to get full date in android?

I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();

Convert long time difference to format HH:mm [Java]

How can I convert the difference of the current time a given time to create a string with the time format: HH:mm ? ex. 18:36
I did the following but, it is not 24Hour format, it will add AM/PM to the end, and it is 3 hours off.
java.util.Date today = new java.util.Date();
java.sql.Timestamp ts1 = new java.sql.Timestamp(today.getTime());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
java.util.Date parsedDate = dateFormat.parse(time);
java.sql.Timestamp ts2 = new java.sql.Timestamp(parsedDate.getTime());
long nowTime = ts1.getTime();
long givenTime = ts2.getTime();
long timeDiff = givenTime - nowTime;
//convert to string
java.util.Date d = new java.util.Date(timeDiff);
result = DateFormat.getTimeInstance(DateFormat.SHORT).format(d);
//Outputs: 6:56 PM for example
Once easy thing you can do is call getTime() for both dates and then subtract them like so:
long timeDiff = today.getTime() - ts1.getTime()
That should give you the difference in miliseconds between the two times. After that you know that one second is 1k miliseconds, 1min i 60s, 1h is 60 minutes and so on.
Take a look at Commons Lang DurationFormatUtils.
Or Joda-Time's PeriodFormatter.

Categories