Passing a String to Date in Java [duplicate] - java

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 7 years ago.
I see that this is deprecated in Java:
Date origin = new Date("July 5, 2318 12:00:00");
What I'm trying to figure out is what I can do to get that exact same functionality. The full context of my example is this:
Date origin = new Date("July 5, 2318 12:00:00");
double stardatesPerYear = 56844.9 * 34367056.4;
double milliseconds = origin.getTime() + stardatesPerYear;
Date dateResult = new Date();
dateResult.setTime((long)milliseconds);
The result of that is that dateResult will a Date object with the following string representation:
Sat May 31 12:24:44 CDT 2380
I'm not concerned about the exact format of the date as I am the accuracy of the result as well as the fact that it can be parsed.
I've seen references to using Calendar and SimpleDateFormat but none of those seem to get me the same output, likely because I'm doing something wrong.
UPDATE ON POSSIBLE DUPLICATE:
I don't know if my question is a duplicate as suggested, but it may be. I tried some examples like this:
String string = "July 5, 2318";
DateFormat format = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH);
try {
Date date = format.parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
That seems like a lot to replace my original Date origin statement.
I guess what I'm curious about is given my full code example, which is this:
Date origin = new Date("July 5, 2318 12:00:00");
double stardatesPerYear = 56844.9 * 34367056.4;
double milliseconds = origin.getTime() + stardatesPerYear;
Date dateResult = new Date();
dateResult.setTime((long)milliseconds);
What's the most effective and efficient code to replace the first line of that code, since it is indicated to me that my first line is using deprecated functionality?

This works, tested in Java 8:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MMMM d, yyyy HH:mm:ss");
Date origin = Date.from(LocalDateTime.parse("July 5, 2318 12:00:00", dtf).toInstant(ZoneOffset.UTC));

Using SimpleDateFormat one line is changed to two lines:
DateFormat dateformat = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss", Locale.US);
Date date = dateformat.parse("July 5, 2318 12:00:00");
To get same output:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy hh:mm:ss", Locale.US);
Date date = fmt.parse("July 5, 2318 12:00:00");
date.setTime(date.getTime() + (long)stardatesPerYear);
3 lines vs. 4 lines (I don't count stardatesPerYear initialization) :)

You can use any of this way:
1)
SimpleDateFormat sdf = new SimpleDateFormat("MMMM dd yyyy hh:mm:ss");
String dateInString = "July 5, 2318 12:00:00";
Date date = sdf.parse(dateInString);
2)
Calendar calendar = new GregorianCalendar(2318,Calendar.JULY,5, 12, 0, 0);
Date date = calendar.getTime();
3)
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.YEAR, 2318);
calendar.set(Calendar.MONTH, Calendar.JULY);
calendar.set(Calendar.DAY_OF_MONTH, 5);
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

Related

How add 30 days in current date? [duplicate]

This question already has answers here:
Is SimpleDateFormat in Java work incorrect or I did any mistake? See code sample [duplicate]
(2 answers)
Parsing a string to date format in java defaults date to 1 and month to January
(2 answers)
Closed 3 years ago.
I want to add 30 days in my current date I searched a lot but did not get the proper solution.
my code
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentdate = df.format(date);
try {
c1.setTime(df.parse(currentdate));
c1.add(Calendar.DATE, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(c1.getTimeInMillis());
String dueudate = df.format(resultdate);
Toast.makeText(this, dueudate, Toast.LENGTH_SHORT).show();
} catch (ParseException e) {
e.printStackTrace();
}
The output of this code is :
2019-01-29
I don't why it is showing this output can anyone help me.
You need to use
c1.add(Calendar.DAY_OF_YEAR, 30);
instead of
c1.add(Calendar.DATE, 30);
Try this
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-dd");
Calendar c1 = Calendar.getInstance();
String currentDate = df.format(date);// get current date here
// now add 30 day in Calendar instance
c1.add(Calendar.DAY_OF_YEAR, 30);
df = new SimpleDateFormat("yyyy-MM-dd");
Date resultDate = c1.getTime();
String dueDate = df.format(resultDate);
// print the result
Utils.printLog("DATE_DATE :-> "+currentDate);
Utils.printLog("DUE_DATE :-> "+dueDate);
OUTPUT
2019-06-04 14:43:02.438 E/XXX_XXXX: DATE_DATE :-> 2019-06-04
2019-06-04 14:43:02.438 E/XXX_XXXX: DUE_DATE :-> 2019-07-04
Another easier option, if on Java 8, use the java.time package which provides functions to perform plus/minus on current date of any units of time, example:
import java.time.LocalDate;
LocalDate date = LocalDate.now().plusDays(30);
//or
LocalDate date = LocalDate.now().plus(30, ChronoUnit.DAYS);
Calendar.getInstance() gives you the current time. You don't need to create another Date object for that.
Calendar current = Calendar.getInstance();
current.add(Calendar.DATE, 30);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Date resultdate = new Date(current.getTimeInMillis());
String dueudate = df.format(resultdate);
System.out.println("" + dueudate);
1)Go from date to millis.
2)Create a long variable with value 30L * 24L * 60L * 60L * 1000L.
3)Add this value to the millis you got in step 1
4) Go from this sum back to date again.
Edit: Variables that store millis should be long, not int.
Edit2: Adding "L" besides each number guarantees we won't get an overflow.

How set the time to zero in given format yyyy-MM-dd HH:mm:ss(Java)

I am given an input date string for ex:2015-06-02 12:60:30 and the output should be 2015-06-02 00:00:00 i.e how to set the HH:mm:ss to zero in the given format yyyy-MM-dd HH:mm:ss ?
use yyyy-MM-dd 00:00:00 format instead of yyyy-MM-dd HH:mm:ss
it will change the hours, minutes and seconds to zero instead of actual values
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
String dateValue = dateFormat.format(new Date());
System.out.println(dateValue);
You can try to use this:
calendar.set(Calendar.HOUR_OF_DAY, 0);
Something like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
System.out.println(sdf.format(c.getTime()));
c.set(Calendar.HOUR_OF_DAY, 0);
System.out.println(sdf.format(c.getTime()));
Simply provide a format for the portion of the "date" you want to keep, for example...
String text = "2015-06-02 12:60:30";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(text);
SimpleDateFormat out = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(out.format(date));
Outputs...
2015-06-02 00:00:00
This is a little trick, which is actually described in the JavaDocs
Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.
Emphasis added by me
try this
SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");
String strDate = sm.format(myDate);
If you don't require validation of the input format, you could use a regular expression:
input.replaceAll("\d\d:\d\d:\d\d", "00:00:00")
However, note that this conversion is not necessarily one which yields a valid time: midnight might not be valid, depending upon the date you are converting and its time zone, so this might not yield a valid time. (The start of daylight savings time in Asia/Gaza is the oft-cited example).
Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR,2015);
cal.set(Calendar.MONTH,6);
cal.set(Calendar.HOUR_OF_DAY,2);
cal.set(Calendar.MINUTE,0);
cal.set(Calendar.SECOND,0);
cal.set(Calendar.MILLISECOND,0);
Date d = cal.getTime();
And to format it you can use:
SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String formatted = sdFormat.format(cal.getTime());

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

How to change the format of date in java [duplicate]

This question already has answers here:
How can I change the date format in Java? [duplicate]
(10 answers)
Closed 9 years ago.
I have a string and i need to convert it to date in the "YYYY-mm-dd" format which i'm unable to do. I checked the similar post on stckoverflow but didnt help so i'm posting this query.
String stringDate = "Dec 13, 2013";
I need this to be convert to
Date reportDate = 2013-12-13";
when i use simpledateformat i got unparsable date. Please help
Check this out:
try {
SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd");
String stringDate = "Dec 13, 2013";
Date date = format1.parse(stringDate);
System.out.println(format2.format(date));
} catch (ParseException exp) {
// Take appropriate action
}
Output: 2013-12-13
In programming a very important skill is taking information that is close to what you need and using it to find what you do need.
Look at the link in the comments and you can see:
http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
Read that and you have what you need to adjust the answer there to give the results you want.
Use SimpleDateFormat as here:
new_date is your Date
String stringDate = "Dec 13, 2013";
SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-DD");
Date new_date=format.parse(stringDate);
String date="Your date";
SimpleDateFormat format = new SimpleDateFormat("MMM DD, YYYY");
Date d= format.parse(date);
DateFormat newFormat = new SimpleDateFormat("YYYY-MM-DD");
System.out.println(newFormat.format(d));
I would do something like:
SimpleDateFormat parser = new SimpleDateFormat("MMM dd, yyyy");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date reportDate = parser.parse(stringDate)
String result = formatter.format(reportDate);

Format current date to show day of the week [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 6 years ago.
I want to show the current date in my application like this:
Thu, May 2, 2013
I already have the following code to get the current date
Calendar c = Calendar.getInstance();
Time time = new Time();
time.set(c.get(Calendar.DAY_OF_MONTH), c.get(Calendar.MONTH),
c.get(Calendar.YEAR));
How can I format this Time object to the string I need?
This does what you want
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
String strDate = sdf.format(cal.getTime());
System.out.println("Current date in String Format: " + strDate);
Where strDate can be displayed in your textView or whatever
Maybe you can use it.
This example displays the names of the weekdays in short form with the help of DateFormatSymbols().getWeekdays() method of DateFormatSymbols class.
import java.text.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Date dt = new Date(1000000000000L);
DateFormat[] dtformat = new DateFormat[6];
dtformat[0] = DateFormat.getInstance();
dtformat[1] = DateFormat.getDateInstance();
dtformat[2] = DateFormat.getDateInstance(DateFormat.MEDIUM);
dtformat[3] = DateFormat.getDateInstance(DateFormat.FULL);
dtformat[4] = DateFormat.getDateInstance(DateFormat.LONG);
dtformat[5] = DateFormat.getDateInstance(DateFormat.SHORT);
for(DateFormat dateform : dtformat)
System.out.println(dateform.format(dt));
}
}
output:
9/9/01 7:16 AM
Sep 9, 2001
Sep 9, 2001
Sunday, September 9, 2001
September 9, 2001
9/9/01
Source
Use this
SimpleDateFormat formatter = new SimpleDateFormat("EEE, MMM dd,yyyy");
String formattedDate = formatter.format(new Date(System.currentTimeMillis()));
Log.e("formattedDate",formattedDate);
I will suggest to use java.text.SimpleDateFormat instead.
public static void main(String[] args) {
Date date=new Date();
String format = new SimpleDateFormat("EEE,MMM d,yyyy ").format(date);
System.out.println(format);
}
SimpleDateFormat dateformat= new SimpleDateFormat("dd,MM,yyyy");
String strdate = dateformat.format(new Date(System.currentTimeMillis()));
Oops, I'm a bit slow.

Categories