How to convert this Date string into a long? [duplicate] - java

This question already has answers here:
Parsing ISO 8601 date format like 2015-06-27T13:16:37.363Z in Java [duplicate]
(2 answers)
Closed 6 years ago.
I am having issues converting a String that has this format for date from the server into a long?
Example Date String - "2016-07-04T00:02:34.457Z" (Note this is a string)
I tried this below but needs try catch around gmt, when I add it and a not null around cmtDt - then I initialize cmtDt to 0 pre setting it on the bottom and it is always 0.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
formatter.setTimeZone(tz);
Date gmt = formatter.parse(comment.getDateCommented());
cmtDt = gmt.getTime();

First, your input String includes milliseconds (and your format does not). Second, your input String includes a literal Z (which is presumably to indicate a UTC timezone). Finally, getting your system timezone and assigning it to the formatter isn't reliably going to be UTC. You need something like,
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
} catch (Exception e) {
e.printStackTrace();
}
Which I ran, and got
1467590554457

Your format string for the SimpleDateFormat needs to be:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
My test code that works is:
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println("cmtDt = " + cmtDt);

The format in SDF needs to be fixed. The following will help you.
Calendar c = Calendar.getInstance();
TimeZone tz = c.getTimeZone();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX");
formatter.setTimeZone(tz);
Date gmt = formatter.parse("2016-07-04T00:02:34.457Z");
long cmtDt = gmt.getTime();
System.out.println(cmtDt);
Prints : 1467599640457

Related

How to convert dd/MM/yyyy format date to ccyy/MM/dd format in java? [duplicate]

This question already has answers here:
How do I convert the date from one format to another date object in another format without using any deprecated classes?
(10 answers)
Closed 4 years ago.
I am facing an issue while converting dd/MM/yyyy format date to ccyy/MM/dd using Java. Can someone, please help me on this? It would be great If I get some example.
Here is my code## Example##
SimpleDateFormat dateFormat1 = new SimpleDateFormat("ddMMyyyy");
Date date1 = new Date();
LocalDate date = DateTimeFormat.forPattern("ddMMyyyy").parseLocalDate(dateFormat1.format(date1));
System.out.println("Century=" + date.getCenturyOfEra());
String usFormat = DateTimeFormat.forPattern("ccyy/MM/dd").print(date);
System.out.println(usFormat);
Thanks in advance.
Actually CCYYMMdd format is same as yyyyMMdd format since CC (century) is year (integer divide by 100) according to ISO 8601 you can read more in this post
converting dd/MM/yyyy date to ccyy/MM/dd date is simple
you can try this approach:
// define date source format
SimpleDateFormat sourceformat = new SimpleDateFormat("dd/MM/yyyy");
// define date target format that you want to convert to it
SimpleDateFormat targetformat = new SimpleDateFormat("yyyy/MM/dd");
// parse the input date as string with source format
// and then format it to the required target format
String dateAsString = "02/08/2018";
Date date = sourceformat.parse(dateAsString);
System.out.println(targetformat.format(date));
Output:
2018/08/02
Here is the solution for this
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
String currentDate = dateFormat.format(date);
System.out.println("currentData::"+currentDate);
DateTime dt = new DateTime(dateFormat.parse(currentDate));
System.out.println("DT::"+dt);
DateTimeFormatter fmt = DateTimeFormat.forPattern("CCYY/MM/DD");
String str = fmt.print(dt);
System.out.println("CC Date::"+str);

Applying timezone to date format not working [duplicate]

This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 6 years ago.
In my Android app I have a string like this, String date = "2016-09-24T06:24:01Z";
I use this code to turn it into a nicer looking date format:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
dateFormat.setTimeZone(TimeZone.getDefault());
DateFormat formatted = new SimpleDateFormat(format);
Date result = dateFormat.parse(date);
dateString = formatted.format(result);
However it's not applying the timezone. I've tried setting it on both dateFormat and formatted and no matter what I do it still comes back with 6:24 AM.
Shouldn't TimeZone.getDefault() be looking at the timezone on the device running the app and adjusting the time accordingly?
As your are using java.util.date which have no Time Zone. It represent UTC/GMT no Time Zone offset. See below thing.
so change this line
dateFormat.setTimeZone(TimeZone.getDefault());
to this
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
or this
dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
If you know the current time zone:
TimeZone tzone = TimeZone.getTimeZone("America/Los_Angeles");
tzone.setDefault(tzone);
If you do not know the current timezone:
Calendar cal = Calendar.getInstance();
long milliDiff = cal.get(Calendar.ZONE_OFFSET);
// Got local offset, now loop through available timezone id(s).
String [] ids = TimeZone.getAvailableIDs();
String name = null;
for (String id : ids) {
TimeZone tz = TimeZone.getTimeZone(id);
if (tz.getRawOffset() == milliDiff) {
// Found a match.
name = id;
break;
}
}
TimeZone tzone = TimeZone.getTimeZone(name);
tzone.setDefault(tzone);

Java DateFormat conversion automatically increases hour by 1

I am trying to take date in string and its input format string and converting the date in output format. However after conversion into Date, the java code increases the number of hours by one. I am not able to understand what causes the bug.
My Code:
try {
DateFormat outputFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
DateFormat inputFormat = new SimpleDateFormat(format);
Date date = inputFormat.parse(parameterValue);
parameterValue = outputFormat.format(date);
return parameterValue;
} catch (ParseException ex) {
// take action
}
format string: ddMMMyyyy / hh:mm z
Input Date: 07DEC2015 / 10:02 GMT
Output Date: 07/12/2015 11:02:00
outputFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
resolved it.
If you don't want to use timezone, in java 8 you can use LocalDate/LocalTime/LocalDateTime:
LocalDateTime localDateTimeInstance = LocalDateTime.parse(dateToBeConverted, DateTimeFormatter.ofPattern(formatOfDateToBeConverted));
return localDateTimeInstance.format("dd/MM/yyyy hh:mm:ss");
/*
Also check out ZoneDate, ZoneTime (for timezone)
Checkout - LocalDate, LocalTime
*/

Java- milliseconds (SSS) not being parsed with SimpleDateFormat [duplicate]

This question already has answers here:
Java date is not preserving milliseconds in conversion with simple date format
(5 answers)
Closed 7 years ago.
Basically I'm attempting to parse date/time to Java, but having issues when trying to parse the milliseconds.
Example of data to be parsed: a[0] = 16/03/2015, a[1] = 10:00:18.120
I read in the two values and concatenate them.
Getting: dateTime = (java.lang.String) "16/03/2015 10:00:18.120"
As you can see the string has the milliseconds when i debug it. From here I parse it to SimpleDateFormat. It works- however the milliseconds are not displayed
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime;
dateTime= a[0]+" "+a[1];
Date d = df.parse(dateTime);
Current output: d = (java.util.Date) Mon Mar 16 10:00:18 GMT 2015
Thanks for your help.
Your code is fine, but not your interpretation of the result. As correctly mentioned in one comment, the method toString() of class java.util.Date does not output the millisecond part. But the millisecond part is still part of the state of your result object. Proof:
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = "16/03/2015 10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(d); // Mon Mar 16 10:00:18 CET 2015
System.out.println(d.getTime()); // 1426496418120
System.out.println("millisecond-part=" + (d.getTime() % 1000)); // millisecond-part=120
So all is fine. You can even format your result back to a string using the same (or another instance of SimpleDateFormat - maybe with different pattern, locale and timezone).
If java.util.Date was correctly implemented as value-type then the inventors of that class would have taken care of making the output of toString() representing the whole exact state of the object but it has not happened - another example why this class is broken.
Using DateFormat.format(Date date) function might meet your requirement
Date date = new Date();
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime=df.format(date);
String[] a=dateTime.split(" ");
System.out.println(a[0]+" "+a[1]);
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss.SSS",Locale.ENGLISH);
String dateTime;
dateTime= "03/16/2015"+" "+"10:00:18.120";
Date d = df.parse(dateTime);
System.out.println(df.format(d));
Try this:
String[] a = new String[]{"16/03/2015", "10:00:18.120"};
DateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.SSS", Locale.ENGLISH);
String dateTime = a[0] + " " + a[1];
try {
Date d = df.parse(dateTime);
System.out.println(d.getTime());//Returns milliseconds
} catch (ParseException ex) {
Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
}
The result: 1426492818120

convert milliseconds to date [duplicate]

This question already has answers here:
How to convert currentTimeMillis to a date in Java?
(13 answers)
Closed 8 years ago.
Server sending me time as 1390361405210+0530 so if I want to convert this in to date then should I have to add 0530 into 1390361405210 and then calculate date and time?
Any suggestion should be appreciated.Thanks
How about this.
long currentDateTime = 1390361405210L;
Date currentDate = new Date(currentDateTime);
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss Z");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+530"));
System.out.println(sdf.format(currentDate));
public static void main( String[] args )
{
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
long milliSeconds=1390361405210L;
Date date = new Date(milliSeconds);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
System.out.println(formatter.format(calendar.getTime()));
System.out.println(formatter.format(date));
}
If we consider that the first part of the String is the number of milliseconds since the epoch, and the second part is a timezone indication (in that case, IST, Indian Standard Time), you can get a readable date like this :
final String jsonDate = "1390361405210+0530";
final Date date = new Date(Long.parseLong(jsonDate.substring(0, jsonDate.length() - 5)));
final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.FULL, Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT" + jsonDate.substring(jsonDate.length() - 5)));
System.out.println(format.format(date));
Output:
January 22, 2014 9:00:05 AM GMT+05:30

Categories