Hi I have a String like this "01-09-2015"
I need to convert this string to long.
I have tried using
String date = "01-09-2015";
Long dateLong = Long.getLong(date);
Long dateLong = Long.valueOf(date);
Long dateLong = Long.valueOf(date,36);
Long dateLong = Long.parseLong(date);
Still no help. Everything returns be NumberFormatException.
Anyone please help.
Thanks in advance.
EDIT
Guys, I will send in a String, which is of course a date like "08-01-2015". For each unique string which I pass, I need a unique long value. Thats all.
You have to convert it to Date first before changing it to Long
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yy");
Date d = format.parse("01-09-2015");
long milliseconds = d.getTime();
I recommend you split the input on -, then convert the three date parts to int; and then concatenate them into a long. Something like,
String date = "01-09-2015";
String[] arr = date.split("-");
int yyyy = Integer.valueOf(arr[2]);
int mm = Integer.valueOf(arr[0]);
int dd = Integer.valueOf(arr[1]);
long dateLong = (yyyy * 10000) + (mm * 100) + dd;
System.out.println(dateLong);
Output is (the unique, per date)
20150109
Note This is in keeping with ISO 8601; the linked Wikipedia article says (in part)
ISO 8601 Data elements and interchange formats – Information interchange – Representation of dates and times is an international standard covering the exchange of date and time-related data.
Related
I'm parsing a timestamp which is "2022-01-12T17:17:34.512492+0000", this format is "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ" (ISO8601).
I want to convert it in epoch unix time, I'm using java.text.SimpleDateFormat.
I tried two methods but both don't work:
1- First Method
val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'ZZZZ'")
val date = df.parse(parsed.toString)
val epoch = date.getTime
Error showed:
java.text.ParseException: Unparseable date: "2022-01-12T17:17:34.512492+0000"
2- This second Method shows an output but is incorrect
val parsed = "2022-01-12T17:17:34.512492+0000"
val df: SimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS'+0000'")
val date = df.parse(parsed.toString)
val epoch = date.getTime
println(epoch)
Output:
1642004766492
If you convert this epoch to HUMAN DATE: "Wednesday, 12 January 2022 16:26:06.492"
The hours,minutes and seconds are wrong.
SimpleDateFormat is outdated, as Gael pointed out.
The Time API now supports up to nanoseconds, so microseconds are not an issue here. You should use DateTimeFormatter with ZonedDateTime. Your pattern is slightly wrong. Checking the docs for Offset Z:
Offset Z: This formats the offset based on the number of pattern
letters. One, two or three letters outputs the hour and minute,
without a colon, such as '+0130'. The output will be '+0000' when the
offset is zero. Four letters outputs the full form of localized
offset, equivalent to four letters of Offset-O. The output will be the
corresponding localized offset text if the offset is zero. Five
letters outputs the hour, minute, with optional second if non-zero,
with colon. It outputs 'Z' if the offset is zero. Six or more letters
throws IllegalArgumentException.
You can also print the time using toInstant to make sure it was parsed correctly:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
val parsed = "2022-01-12T17:17:34.512492+0000"
val p = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZ"
val dtf = DateTimeFormatter.ofPattern(p)
val zdt = ZonedDateTime.parse(parsed, dtf)
println(zdt.toInstant) // 2022-01-12T17:17:34.512492Z
println(zdt.toInstant.toEpochMilli) // 1642004254512
Here is a nice article that explains in detail converting an ISO 8601 in Java. The comments at the end are particularly useful, as it shows the difference between the different patterns used.
looks like epoch has data in internal datetime format.
and you should convert it to string format
like this in java
public static String dateToString(Date d, String string_format) {
String result = "";
if(d != null) {
result = new SimpleDateFormat(string_format).format(d);
}
return result;
}
The timestamp you have has microseconds precision. Such precision is not supported by SimpleDateFormat. Also, Unix epoch time is usually up to milliseconds precision.
Possible solution here is to explicitly round the microseconds to milliseconds in the string before parsing, then use the yyyy-MM-dd'T'HH:mm:ss.SSSZ format.
String parsed = "2022-01-12T17:17:34.512492+0000";
String upToSeconds = parsed.substring(0, "yyyy-MM-ddTHH:mm:ss".length());
String microseconds = parsed.substring("yyyy-MM-ddTHH:mm:ss.".length(), "yyyy-MM-ddTHH:mm:ss.".length() + "SSSSSS".length());
String timezone = parsed.substring("yyyy-MM-ddTHH:mm:ss.SSSSSS".length());
String roundedMilliseconds = new BigDecimal(microseconds).divide(new BigDecimal("1000"), 0, RoundingMode.HALF_UP).toString();
String reformatted = upToSeconds + "." + roundedMilliseconds + timezone;
System.out.println(reformatted); // 2022-01-12T17:17:34.512+0000
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
long epoch = sdf.parse(reformatted).getTime();
System.out.println(epoch); // 1642007854512
System.out.println(Instant.ofEpochMilli(epoch)); // 2022-01-12T17:17:34.512Z
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'));
}
I am posting DateTime as JSON and it becomes "/Date(1512839439513)/"
i simply want to convert
"/Date(1512839439513)/" to java.util.Date
I have tried this
String date = finalObject.getString("DateCreated");
String datereip = date.replaceAll("\\D+","");
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
But did not worked...
The way you extract the milliseconds from the string seems to be the problem.
You can try this to extract needed data from the string:
String date = finalObject.getString("DateCreated");
String temp = date.substring(date.indexOf("(") + 1);
String datereip = date.substring(0, date.indexOf(")"));
Long timeInMillis = Long.parseLong(datereip);
Date date1=new Date(timeInMillis);
This assumes that the date string will have only one pair of parenthesis. Also, there are better ways to extract string between 2 chars with Java but that is a topic of another question.
I've a code for generating random date strings. However I came to find that when I generate a random timestamp, it contains some precision decimal points to seconds field. How ever my SimpleDateFormat does not contain such precision values, does anyone know what is wrong here, and how can I remove or control the precision values ?
Code
long rangeBegin = Timestamp.valueOf("2015-01-01 00:00:00").getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date currentDate = new Date();
String currentDateString = simpleDateFormat.format(currentDate);
long rangeEnd = Timestamp.valueOf(currentDateString).getTime();
long diff = rangeEnd - rangeBegin + 1;
Timestamp randomTimestamp = new Timestamp(rangeBegin + (long)(Math.random() * diff));
Sample output
randomTimestamp = 2015-02-20 02:36:00.646
Thanks
Edit :
String randomTimestampString = String.valueOf(randomTimestamp).split("\\.")[0];
The number after the decimal is for fractional precision, i.e. nanoseconds.
You could get rid of it by formatting or simply stripping them off using the String.substring() method.
randomTimestamp = 2015-02-20 02:36:00.646
According to the Timestamp javadoc this 646 means the nanoseconds for precision
I looked through all possible answer here but I am having hard time to figure this thing out.
I have Json date in a String. I want to convert into a Java Date without losing time.
Also I would like to convert from Java Date to Json Date string.
Here what I have.
String jsonDateString = "/Date(1295157600000-0600)/";
There are 2 parts in your time : the local time in milliseconds, and the offset in hours and minutes. You have to parse them and "add" them to get the milliseconds UTC.
You may do it using this function :
private static Pattern p = Pattern.compile("\\((\\d+)([+-]\\d{2})(\\d{2})\\)");
public static Date jd2d(String jsonDateString) {
Matcher m = p.matcher(jsonDateString);
if (m.find()) {
long millis = Long.parseLong(m.group(1));
long offsetHours = Long.parseLong(m.group(2));
long offsetMinutes = Long.parseLong(m.group(3));
if (offsetHours<0) offsetMinutes *= -1;
return new Date(
millis
+ offsetHours*60l*60l*1000l
+ offsetMinutes*60l*1000l
);
}
return null;
}
To make "back" a JSON date, I would simply encode the UTC time :
String jsonDate = "/Date("+date.getTime()+"+0000)/";