how to convert java string to Date object [duplicate] - java

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 9 years ago.
I have a string
String startDate = "06/27/2007";
now i have to get Date object. My DateObject should be the same value as of startDate.
I am doing like this
DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Date startDate = df.parse(startDate);
But the output is in format
Jan 27 00:06:00 PST 2007.

You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}

"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".
So, try to change the code to:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
Edit:
A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting.
When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws Exception {
String startDateString = "06/27/2007";
// This object can interpret strings representing dates in the format MM/dd/yyyy
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Convert from String to Date
Date startDate = df.parse(startDateString);
// Print the date, with the default formatting.
// Here, the important thing to note is that the parts of the date
// were correctly interpreted, such as day, month, year etc.
System.out.println("Date, with the default formatting: " + startDate);
// Once converted to a Date object, you can convert
// back to a String using any desired format.
String startDateString1 = df.format(startDate);
System.out.println("Date in format MM/dd/yyyy: " + startDateString1);
// Converting to String again, using an alternative format
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String startDateString2 = df2.format(startDate);
System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
}
}
Output:
Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007

try
{
String datestr="06/27/2007";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy");
date = (Date)formatter.parse(datestr);
}
catch (Exception e)
{}
month is MM, minutes is mm..

The concise version:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
Add a try/catch block for a ParseException to ensure the format is a valid date.

var startDate = "06/27/2007";
startDate = new Date(startDate);
console.log(startDate);

Related

Convert GMT time to specific String Format [duplicate]

This question already has answers here:
Illegal pattern character 'T' when parsing a date string to java.util.Date
(4 answers)
Closed 5 years ago.
I have specific case that I must take the date field, convert it to GMT time and then to convert it to specific String format.
This gives the GMT time:
public static void main(String[] args) {
Date rightNow = Calendar.getInstance().getTime();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(rightNow));
String gmtDate=gmtFormat.format(rightNow);
}
Now I need to that GMT time convert to String format yyyy-MM-ddTHH:mm:ssZ
Example current time in my time zone is 17:10:00, in GMT 15:10:00 so it means final output should be 2017-08-07T15:10:00Z
I tried this code to add:
String pattern = "yyyy-MM-ddTHH:mm:ssZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(gmtDate);
System.out.println(date);
But of course I am getting the exception because string cannot be converted like this, but I need something similar.
Merge your 2 codeblocks together:
public static void main(String[] args) {
Date rightNow = Calendar.getInstance().getTime();
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
DateFormat gmtFormat = new SimpleDateFormat(pattern);
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(rightNow));
}
Or "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" as per JavaDoc...

issue in converting the date from string to date type

below is the code I have used to add the number of days to the existing date..which gave me string output and I want that to be converted to Date format again...I have tried formating but it gave the out put -->
Date date = sdf.parse(dt);
sysout (date ) --giving me -- Mon May 05 00:00:00 PDT 2008
but I want it as YYYY-MM/DD
sdf.format(date) --Gives me 2008-05-05 which I am looking but it is a string object...but I want this to be converted to DATE type
String dt = "2008-01-01"; // Start date
System.out.println("start date "+dt);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 125); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("c.getTime() "+c.getTime());
System.out.println("end date "+dt);
Date date = sdf.parse(dt);
System.out.println("last but one date in DATE form -->" +date);
System.out.println("last formatted date in string form "+sdf.format(date));
You created the format right.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
but you are using it incorrectly. you should use
sdf.format(your_unformated_date);
Here is a sample code that will convert date from String to Date type using SimpleDateFormat Class:
public static void convert()
{
String str="10:25:35";
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(str));
}

Incorrect UNIX timestamp from String Date

I am trying to convert a date in String format into UNIX timestamp, I am able to convert it but when I check the timestamp it displays incorrect date.
I am using the following code to convert a Date in String to Unix timestamp:
String selected_date = "16/11/2015 1:34 am";
datetime.setText(selected_date);
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy hh:mm a");
Date date = null;
try {
date = dateFormat.parse(selected_date);
} catch (ParseException e) {
e.printStackTrace();
}
long unixTime = (long)date.getTime()/1000;
The output UNIX timestamp is: 1460309640
But when I convert that timestamp using a web tool it returns: 4/11/2016, 1:34:00 AM
The format
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy hh:mm a");
is not compatible with the string
String selected_date = "16/11/2015 1:34 am";
16 can't be a month!
2015 is not a year in two digits format
The right format seems to be (not sure if kk or KK depending on hours if 0 based or not)
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy kk:mm a");

How to format a date String into desirable Date format

I was trying to format a string into date.
For this I have written a code:-
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdf.format( cal.getTime() ));
This is fine..
But now I want to convert a string into a date formatted like above..
For example
String dt="2010-10-22";
And the output should be like this:-
2010-10-22T00:00:00
How do I do this?
String dt = "2010-10-22";
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition ps = new ParsePosition(0)
Date date = sdfIn.parse(dt, pos)
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println(sdfOut.format( date ));
This should do it for you, remember to wrap it in a try-catch block just in case.
DateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try
{
Date today = dt.parse("2010-10-22T00:00:00");
System.out.println("Your Date = " + dt.format(today));
} catch (ParseException e)
{
//This parse operation may not be successful, in which case you should handle the ParseException that gets thrown.
//Black Magic Goes Here
}
If your input is going to be ISO, you could also look at using the Joda Time API, like so:
LocalDateTime localDateTime = new LocalDateTime("2010-10-22");
System.out.println("Formatted time: " + localDateTime.toString());
The same class you use for output formatting of dates can also be used to parse dates on input.
SimpleDateFormat reference
To use your example, to parse the sample date:
String dt = "2010-10-22";
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dateFormatter.parse(dt));
The fields that are not specified (ie. hour, minutes, etc) will be 0. So your same code can be used to format the date on output.
Date Format Example
Containing the Conversion of String Date object from one format to another

Java date format real simple

how would you write te date if i have a date and all i want is the month and the day like this (mm/dd) and then turn the month like this July, 08
Let me see if I understood well.
You have a date like "07/08" and you want "July, 08"?
You could try SimpleDateFormat
import java.text.SimpleDateFormat;
import java.text.ParseException;
class Test {
public static void main( String [] args ) throws ParseException {
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
System.out.println( out.format( in.parse("07/08") ) );
// Verbose
//String input = "07/09";
//Date date = in.parse( input );
//String output = out.format( date );
//System.out.println( output );
}
}
Use:
Format formatter = new SimpleDateFormat("MMMM, dd");
String s = formatter.format(date);
Formatting a Date Using a Custom Format
The SimpleDateFormat is your friend here. If you already have a java.util.Date object, just format it using the desired pattern (refer to the javadoc for details on date and time patterns):
SimpleDateFormat out = new SimpleDateFormat("MMMM, dd");
String s = out.format(date); // date is your existing Date object here
(EDIT: I'm adding some details as the original question is unclear and I may have missed the real goal.
If you have a String representation of a date in a given format (e.g. MM/dd) and want to transform the representation, you'll need 2 SimpleDateFormat as pointed out by others: one to parse the String into a Date and another one to format the Date.
SimpleDateFormat in = new SimpleDateFormat("MM/dd");
Date date = in.parse(dateAsString); // dateAsString is your String representation here
Then use the code snippet seen above to format it.)
the month and the day like this (mm/dd) and then turn the month like this July, 08
So you want to convert MM/dd to MMMM, dd? So you start with a String and you end up with a String? Then you need another SimpleDateFormat instance with the first pattern.
String dateString1 = "07/08";
Date date = new SimpleDateFormat("MM/dd").parse(dateString1);
String dateString2 = new SimpleDateFormat("MMMM, dd").format(date);
System.out.println(dateString2); // July, 08 (monthname depends on locale!).

Categories

Resources