Convert String in milliseconds to Date Object (JAVA) [duplicate] - java

This question already has answers here:
Convert millisecond String to Date in Java
(5 answers)
Closed 6 years ago.
Is there a way for me to convert a String in milliseconds to a Date object?
In my program, I have to convert a Date in MM/dd/yyyy format to milliseconds, but then I have to pass that to a Date object.
Below, dateStringFinal is a String with the format "MM/dd/yyyy" already.
Calendar dateInCal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
try {
dateInCal.setTime(sdf.parse(dateStringFinal));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dateInMilli = String.valueOf(dateInCal.getTimeInMillis());
Then I have to set a date variable
someBean.setBeginDate(dateInMilli);
But dateInMilli should be a Date object. Any ideas?

new Date(Long.valueOf(dateInMs));
However, SimpleDateFormat.parse() already returns a Date.

How about using Long.parseLong(String):
someBean.setBeginDate(Long.parseLong(dateInMilli));

You can get Date immediately from calendar with calendar.getTime().

dateInCal.getTimeInMillis() returns Long. keep it in Long instead of String. And then use Date constructor that takes Long:
Long dateInMilli = dateInCal.getTimeInMillis();
someBean.setBeginDate(new Date(dateInMilli));

Related

Convert "2020-10-31T00:00:00Z" String Date to long [duplicate]

This question already has answers here:
Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST
(9 answers)
How to validate the DateTime string format "2018-01-22T18:23:00.000Z" in Java?
(2 answers)
parsing date/time to localtimezone
(2 answers)
Closed 3 years ago.
I am having Input Date as "2020-10-31T00:00:00Z". i want to parse this Date to get Long milliseconds.
Note: Converted milliseconds should be in Sydney Time (ie GMT+11).
FYI,
public static long RegoExpiryDateFormatter(String regoExpiryDate)
{
long epoch = 0;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("GMT+11"));
Date date;
try {
date = df.parse(regoExpiryDate);
epoch = date.getTime();
} catch (ParseException e) {
System.out.println("Exception is:" + e.getMessage());
e.printStackTrace();
}
System.out.println("Converted regoExpiryDate Timestamp*************** " + epoch);
return epoch;
}
Output: 1604062800000 which gives Date as 30/10/2019 by using Epoch Converter, but in input i'm passing 31st as Date.
Can anyone please clarify this?
By doing df.setTimeZone(TimeZone.getTimeZone("GMT+11"));, you are asking the date formatter to interpret your string in the GMT+11 time zone. However, your string shouldn't be interpreted in that timezone. See that Z in the string? That stands for the GMT time zone, so you should have done this instead:
df.setTimeZone(TimeZone.getTimeZone("GMT"));
In fact, your string is in the ISO 8601 format for an Instant (or a "point in time", if you prefer). Therefore, you could just parse it with Instant.parse, and get the number of milliseconds with toEpochMilli:
System.out.println(Instant.parse("2020-10-31T00:00:00Z").toEpochMilli());
// prints 1604102400000
Warning: you shouldn't really use SimpleDateFormat anymore if the Java 8 APIs (i.e. Instant and such) are available. Even if they are not, you should use NodaTime or something like that.

JAVA - Format a custom string using SimpleDateFormat [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Java string to date conversion
(17 answers)
Closed 5 years ago.
I'm having trouble formatting a custom String back to a Date object. What i have:
String customString = "October 14, 2015;
Date date = new Date();
SimpleDateFormat s = new SimpleDateFormat("MM-dd-yyyy");
try {
date = s.parse(customString);
} catch (ParseException e) {
e.printStackTrace();
}
I always get a unappeasable date exception. Any pointers of what i'm doing wrong is appreciated.
Your pattern must be: new SimpleDateFormat("MMM dd,yyyy");
For more informations about SimpleDateFormat see the javadoc
Read the docs, https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html.
The argument of the constructor should have the format of the date you want to input.
For instance, if you want the full month name should have "MMMMM".
Just make the following change and the program will work.
SimpleDateFormat s = new SimpleDateFormat("MMMMM dd, yyyy");

Finding the difference between current time and last updated time on Parse backend [duplicate]

This question already has answers here:
Calculating the difference between two Java date instances
(45 answers)
Closed 7 years ago.
I'm trying to write a Java script that computes the time difference between the current date and the last updated time stored on our Parse backend. Can anyone help me spot the bug in my code? You'd think this isn't so bad, but I've looked on Stack Overflow for hours to no avail.
//Create a date formatter.
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'LLL'Z'");
//Create a date object for today's date.
Date currentDate=new Date();
//Create a string for the date from parse.
String parseTime = singleClaim.getString("updatedAt");
//Create a string for the current date.
String currentTime=currentDate.toString();
//Initialize the date object for the updatedAt time on Parse.
Date parseDate = null;
//Initialize the date object for the current time.
Date FormattedCurrentDate = null;
try {
//Here, we convert the parseTime string into a date object and format it.
parseDate = formatter.parse(parseTime);
//Here, we convert the currentTime string into a date object and format it.
FormattedCurrentDate = formatter.parse(currentTime);
}
catch (Exception e) {
e.printStackTrace();
}
//Get the time difference from the current date versus the date on Parse.
long difference = FormattedCurrentDate.getTime()-parseDate.getTime();
The combination of these two lines is probably causing your issue:
String currentTime=currentDate.toString();
// ...
FormattedCurrentDate = formatter.parse(currentTime);
The currentTime variable does not contain a properly formatting string that can be comsumed by your formatter.
I also see no need to create such a string, you could just do it as follows:
long difference = currentDate.getTime() - parseDate.getTime();
If you absolutely insist on making a round trip from date to string and back, you would have to create your currentTime string as follows:
currentTime = formatter.format(currentDate);
You should not call toString() to convert Date to String. And why you convert currentTime to String and later parse it to a date? This makes no sence.
//Create a date formatter.
SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'LLL'Z'");
//Create a date object for today's date.
Date currentDate=new Date();
//Create a string for the date from parse.
String parseTime = singleClaim.getString("updatedAt");
//Create a string for the current date.
String currentTime=currentDate.toString();
//Initialize the date object for the updatedAt time on Parse.
Date parseDate = null;
try {
//Here, we convert the parseTime string into a date object and format it.
parseDate = formatter.parse(parseTime);
}
catch (Exception e) {
e.printStackTrace();
}
//Get the time difference from the current date versus the date on Parse.
long difference = currentDate.getTime()-parseDate.getTime();

java ParseException: Unparseable date [duplicate]

This question already has answers here:
Java Unparsable date
(4 answers)
Closed 8 years ago.
I'm trying to convert a timestamp coming from a JSON API to a relative time span string like this:
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
Date date = sdf.parse(item.getTimeStamp());
long milliseconds = date.getTime();
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
milliseconds,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
timestamp.setText(timeAgo);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
The timestamp comes back in JSON like this: 2014-07-01T00:05:20Z
I'm throwing the exception for Unparseable date
What am I doing wrong here?
Z expects timezone value, change your pattern to and you don't need SSS since you don't have milliseconds in input
yyyy-MM-dd'T'HH:mm:ss'Z'

String to GregorianCalendar [duplicate]

This question already has answers here:
Convert a string to a GregorianCalendar
(2 answers)
Closed 9 years ago.
i have this code:
String start = startBox.getText();
String finish = finishBox.getText();
myprogram.addPeriod(start, finish)
addPeriod method has 2 GregorianCalendar as parameters, so how to convert the 2 string into GregorianCalendar?
I tried a couple of ways that i read on this site but they don't work with me
startBox and finishBox are 2 JTextField filled with date in this format: YYYY/MM/DD.
How about this, the steps are self-explanatory but you want to have a handle on an instance of SimpleDateFormat of the pattern in which you have your date.
Parse your Strings to get a Date instance and set your specific date to the respective Calendar instances.
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
String start = startBox.getText();
String finish = finishBox.getText();
GregorianCalendar cal1 = new GregorianCalendar();
cal1.setTime(format.parse(start));
GregorianCalendar cal2 = new GregorianCalendar();
cal1.setTime(format.parse(finish));
myprogram.addPeriod(cal1, cal2);
}
} catch (ParseException e) {
e.printStackTrace();
}

Categories