Java date format real simple - java

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!).

Related

Date in String to Date in Date conversion

I'm having date in String format as "2019-10-30 12:17:47". I want to convert this to an instance of Date along with the time so that I can compare two date obejcts.
This is what I've tried:
String dateString = "2019-10-30 12:17:47" //Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); //sdf
Date d1 = format.parse(dateString);
But here I'm getting exception as "Unparseble date exception".
Kindly help...
What went wrong in your code?
In your format pattern string, yyyy-MM-dd HH-mm-ss, you have got two spaces between the date and the time. Since your date string, 2019-10-30 12:17:47, has got only one space there, your formatter objects by throwing the exception. This was also what Tim Biegeleisen said in a comment. The comment by deHaar is true too: The hyphens between hour, minute and second don’t match the colons in your date string either.
What to do instead?
See the good answer by deHaar
You should really switch to java.time (as already suggested in one of the comments below your question). It isn't more difficult than the outdated temporal classes from java.util but less error-prone and more powerful concerning offsets, time zones, daylight saving time and the multitude of different calendars the world has.
See this little example:
public static void main(String[] args) {
String dateString = "2019-10-30 12:17:47";
// define your pattern, should match the one of the String ;-)
String datePattern = "yyyy-MM-dd HH:mm:ss";
// parse the datetime using the pattern
LocalDateTime ldt = LocalDateTime.parse(dateString,
DateTimeFormatter.ofPattern(datePattern));
// print it using a different (here a built-in) formatting pattern
System.out.println(ldt.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
// or you just use the one defined by you
System.out.println(ldt.format(DateTimeFormatter.ofPattern(datePattern)));
// or you define another one for the output
System.out.println(ldt.format(DateTimeFormatter.ofPattern("MMM dd yyyy HH-mm-ss")));
}
The output on my system looks like this:
2019-10-30T12:17:47
2019-10-30 12:17:47
Okt 30 2019 12-17-47
The date in string you want to format does not match the formatter. See more detail here,
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
#Test
public void test2() {
String dateString = "2019-10-30 12:17:47"; //Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //sdf
try {
Date d1 = format.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
There are two ways to do it
first is your way
String dateString = "2019-10-30 12:17:47"; // Date in String format
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // sdf
Date d1 = format.parse(dateString
second is my way (Local date)
LocalDate resultDate = dateFormat("2019-10-30 12:17:47");
System.out.println(resultDate);
public static LocalDate dateFormat(String textTypeDateTime) {
final DateTimeFormatter dateTimetextFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDate.parse(textTypeDateTime, dateTimetextFormatter);
}

How to format my date with SimpleDateFormat?

I'm trying to set a date format, but when i run this code
String oldstring = "2013-01-1";
System.out.println("oldstring = "+oldstring);
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(oldstring);
System.out.println("datefield = "+date);
i take result:
oldstring = 2013-01-1
datefield = Tue Jan 01 00:01:00 MSK 2013
Why datefield isn't equal 2013-01-1?
At first mm in yyyy-mm-dd mean minute not Month. to set month use MM.
It would be look like this :
Date date = new SimpleDateFormat("yyyy-MM-dd").parse(oldstring);
UPDATE
Try this:
String oldstring = "2013-01-1";
System.out.println("oldstring = "+oldstring);
Date date = new SimpleDateFormat("yyyy-mm-dd").parse(oldstring);
String sdf = new SimpleDateFormat("yyyy-mm-dd").format(date);
System.out.println("datefield = "+sdf);
If you don't use new SimpleDateFormat("yyyy-mm-dd").format(date);
you getting standard date format which include all info. If you want special format you need to use
new SimpleDateFormat("yyyy-mm-dd").format(date);
Also read this article about date formatting
The type of datefield is Date, so the toString method will basically always return the same format, as you are not overriding it.
So what you need to do, is basically:
String oldstring = "2013-01-1";
System.out.println("oldstring = "+oldstring);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(oldstring);
System.out.println("datefield = "+date);
String outDateStr = sdf.format(date);
System.out.println("newstring = "+outDateStr);
Use MM for month. mm is for minutes

how to convert java string to Date object [duplicate]

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);

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

Extract time from date String

How can I format the "2010-07-14 09:00:02" date string to depict just "9:00"?
Use DateTimeFormatter to convert between a date string and a real LocalDateTime object. with a LocalDateTime as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the DateTimeFormatter.
String originalString = "2010-07-14 09:00:02";
LocalDateTime dateTime = LocalDateTime.parse(originalString, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
String newString = DateTimeFormatter.ofPattern("H:mm").format(dateTime); // 9:00
In case you're not on Java 8 or newer yet, use SimpleDateFormat to convert between a date string and a real Date object. with a Date as starting point, you can easily apply formatting based on various patterns as definied in the javadoc of the SimpleDateFormat.
String originalString = "2010-07-14 09:00:02";
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(originalString);
String newString = new SimpleDateFormat("H:mm").format(date); // 9:00
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2010-07-14 09:00:02");
String time = new SimpleDateFormat("H:mm").format(date);
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
A very simple way is to use Formatter (see date time conversions) or more directly String.format as in
String.format("%tR", new Date())
The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:
String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
.format(DateTimeFormatter.ofPattern("H:mm"));
The result is the desired, 9:00.
I'm assuming your first string is an actual Date object, please correct me if I'm wrong. If so, use the SimpleDateFormat object: http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. The format string "h:mm" should take care of it.
If you have date in integers, you could use like here:
Date date = new Date();
date.setYear(2010);
date.setMonth(07);
date.setDate(14)
date.setHours(9);
date.setMinutes(0);
date.setSeconds(0);
String time = new SimpleDateFormat("HH:mm:ss").format(date);
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)

Categories

Resources