This question already has answers here:
Printing out datetime in a specific format in Java?
(4 answers)
Closed 3 years ago.
I want to remove the time from dateAndTime, and also want to have all of them in numeric form like this: 10-10-2019
output: Wed Nov 10 16:39:58 AST 2010
public static void main(String args[]){
//Java calendar in default timezone and default locale
int day =10;
int month =10;
int year =10;
Calendar m = Calendar.getInstance();
m.set(year, month, day);
m.add(day, 10);
System.out.println(" Date :" + m.getTime());
Use SimpleDateFormat. There's a lot of example you can use.
you can use SimpleDateFormat for early versions of java or DateTimeFormatter for java8+.
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
public class DateTests {
public static void main(String[] args) {
//java8+
//recommended
String formattedToday = DateTimeFormatter.ofPattern("MM-dd-YYYY").format(LocalDateTime.now());
System.out.println(formattedToday);
//early versions of java
Calendar today = Calendar.getInstance();
String formatted = new SimpleDateFormat("MM-dd-YYYY").format(today.getTime());
System.out.println(formatted);
}
}
output:
09-18-2019
09-18-2019
Also read Calendar date to yyyy-MM-dd format in java
Related
This question already has answers here:
Parse CIM_DateTime with milliseconds to Java Date
(2 answers)
Closed 2 years ago.
Into a Java application I have this String representing a timestamp containing values like this: 2009-10-17 05:45:14.000
As you can see the string represents the year, the month, the day, the hour, the minute, the second and the millisencond.
I have to convert a String like this into a Date object (if possible bringing also the millisecond information, is it possible?)
How can I correctly implement it?
You can use SimpleDateFormat to parse a given string date according to a given pattern, it also supports milliseconds, like this:
SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
Date date=format.parse("2009-10-17 05:45:14.050");
Since Java 8, you should use the classes in the date-time API
Class LocalDateTime stores a date and a time up to nanosecond precision.
Here is a snippet showing how to parse a string into an instance of LocalDateTime
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class DateTime {
public static void main(String[] args) {
String str = "2009-10-17 05:45:14.000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse(str, formatter);
}
}
This question already has answers here:
How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?
(16 answers)
How to get the current date/time in Java [duplicate]
(28 answers)
How to format a ZonedDateTime to a String?
(3 answers)
Closed 2 years ago.
I want to print the current date in this format -
01-JUN-20 08.55.27.577984000 AM UTC. Tried lot of formats in SimpleDateformat but none is working. What is the right way to print like this?
SimpleDateFormat
You can use the following pattern:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class TimeFormatting {
public static void main(String[] args) {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy hh.mm.ss.SSS a Z");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
String formatted = formatter.format(new Date(2015, 4, 4, 13, 7, 19)); //One example date
System.out.println(formatted);
}
}
This will give the output 04-05-15 11.07.19.000 AM +0000 where +0000 equals to UTC.
Explanation of the pattern dd-MM-yy hh.mm.ss.SSS a Z:
dd = the day
MM = the month
yy = the year
hh = the hour
mm = the minute
ss = the second
SSS = the millisecond. There does not exist a reference to nanoseconds in SimpleDateFormat (see this answer).
a = to show AM/PM
Z = to show the timezone
Additional information
Please note: SimpleDateFormat is deprecated. You should use DateTimeFormatter. One big advantage is that you can also have the nanoseconds (n).
One example:
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.ZoneOffset;
public class TimeFormatting {
public static void main(String[] args) {
ZonedDateTime time = ZonedDateTime.now(ZoneOffset.UTC);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yy hh.mm.ss.n a 'UTC'").withZone(ZoneOffset.UTC);
String timeDate = time.format(formatter);
System.out.println(timeDate);
}
}
Edit:
If you want to have UTC instead of +0000 with SimpleDateFormat you can use dd-MM-yy hh.mm.ss.SSS a zzz instead.
This question already has answers here:
display Java.util.Date in a specific format
(11 answers)
want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format
(11 answers)
Convert String date into java.util.Date in the dd/MM/yyyy format [duplicate]
(1 answer)
return date type with format in java [duplicate]
(1 answer)
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 3 years ago.
I have a requirement to convert String to Date (in dd-MM-yyyy format). But dateformat.parse gives the format with seconds. I need to convert the String date to Date in the same format as mentioned above.
The class Date will always contain both date a nd time information, since it represents an instant in time.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d;
try {
d = fmt.parse("04-12-2019");
System.out.println(d); // Wed Dec 04 00:00:00 CET 2019
} catch (ParseException e) {
e.printStackTrace();
}
}
}
As you can see, hours, minutes, seconds and millis get all set to 0.
If you later want to output the date in string format, you need to use the DateFormat#format(Date) method:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParsingDate {
public static void main(String[] args) {
DateFormat fmt = new SimpleDateFormat("dd-MM-yyyy");
Date d = new Date();
System.out.println(d); // Wed Dec 04 11:24:35 CET 2019
System.out.println(fmt.format(d)); // 04-12-2019
}
}
If you'd rather store only date information, you could use the java.time package and make use of LocalDate.
LocalDate stores only date information, since it does not represent an instant, rather a triple of year, month and date.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ParsingLocalDate {
public static void main(String[] args) {
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate d = LocalDate.parse("04-12-2019", fmt);
System.out.println(d); // 2019-12-04
}
}
If you do not need to use time of day or time zone, you can parse it by LocalDate.
String str = "01-01-2000";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate date = LocalDate.parse(str, formatter);
Note that for day and time people most of the time would want a ZonedDateTime rather than a LocalDateTime. The name is counter-intuitive; the Local in both LocalDate and LocalDateTime means any locality in general rather than a specific time zone.
In most programming languages, date/time types are simply containers for the amount of time which has passed from a given point in time. They don’t have a format.
In the case of Java (AFAIR), time is measured in milliseconds since the Unix Epoch.
Since it's 2019, there is no excuse not to making use of the java.time APIs (or the ThreeTen backport) and you should avoid using the, now effectively deprecated, older APIs
Parse String to LocalDate
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate localDate = LocalDate.parse("08-03-1972", inputFormatter);
Format LocalDate to desired format
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("dd EEE MMM yyyy");
String value = localDate.format(outputFormatter);
System.out.println(value);
which outputs
08 Wed. Mar. 1972
I have tried this code. I got the output but not the right one...
//Iam getting my answer after the following changes below...
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(5,9,2014,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
}
//I made the changes like this.....
Date da = new Date(114,8,5,12,30,0);
OUTPUT: 5 Sep 2014 07:00:00 GMT
This gives me right output... Thanks for your support friends.....
To get the sep 5 as output, shuold be given as 5-9,
Try using simpledateformat:
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "5-9-2014 07:00:00";
Date date = sdf.parse(dateInString);
System.out.println(date);
Quoting from Java Doc
Date(int year, int month, int date, int hrs, int min, int sec)
`Deprecated. As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date, hrs, min, sec) or GregorianCalendar(year + 1900, month, date, hrs, min, sec).`
Avoid using Date constructor (to set dates) at all, incase you insist maintain correct order of parameters, your code should look like this:-
package patternsamp;
import java.io.*;
import java.util.*;
public class Mydate
{
static void test()
{
Date da = new Date(114,9,5,07,00,00);
System.out.println(da.toGMTString());
}
public static void main(String[] args)
{
Mydate.test();
}
Note that I am using 114 in the year (and not 2014), since according to doc
A year y is represented by the integer y - 1900.
Hence to represent 2014 , you have to 2014-1900, which is 114.
if your project imported commons-lang.jar
you can get the Date object from String like this:
DateUtils.parseDate("2014-08-20",new String[]{"yyyy-MM-dd"})
Joda-Time
So much easier and sensible to use the Joda-Time library rather than the notoriously troublesome bundled java.util.Date and .Calendar classes. To specify a year, you specify a year (2014 rather than 114). To specify a month, you specify a month (9 means September rather than 8).
DateTime dateTime = new DateTime( 2014, 9, 5, 7, 0, 0, DateTimeZone.UTC );
If you must have a java.util.Date object, convert.
java.util.Date date = dateTime.toDate();
The problem I'm trying to solve is as follows. In Nepal we use Bikram Sambat (BS) as our Calendar and also use Georgian Calendar (AD). What I'm trying to do is convert a BS to AD and an AD to BS. BS is 56 years and 8 months ahead of AD. For example today: 17th Feb 2013 is 4 (day) 11 (month) 2070 (year) in BS.
package Day10;
import java.util.Date;
/**
* This is my driver class
*/
public class Driver {
public static void main (String[] args){
DateUtils dateUtils = new DateUtils(); //Object creation
Date date=dateUtils.getCurrentDate(); //current date
dateUtils.getAd("10 21 2070"); //method invoke for BS to AD. (It is mm/dd/yyyy BS)
}
}
package Day10;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* This is my Service class for converting date values.
*/
final public class DateUtils {
public Date getCurrentDate(){
SimpleDateFormat dateFormat = new SimpleDateFormat("MMM dd yyyy");//date format
Date date = new Date();//current date
System.out.println(dateFormat.format(date));
return date;
}
//method to convert BS to AD
public Calendar getAd (String bs){
DateFormat dateFormat = new SimpleDateFormat("MM dd yyyy");//date format
Calendar ad = Calendar.getInstance();
//Converting String Value to Calendar Object
try { ad.setTime(dateFormat.parse(bs));
} catch (ParseException e){
System.out.println("Invalid");
}
System.out.println("Your AD date:"+dateFormat.format(bs));
return ad;
}
}
Problem: While trying to change the String format to Calendar could not determine the variable to store the new converted Calendar value.
I'm trying to change the String value to Calendar and subtract 56 years and 8 months from that. Is that a good possible way?
Thanks.
If you just want to add several years/months to a Calendar, you can
do this as follows. But again, this is not real AD to BS conversion.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Test040 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = new GregorianCalendar();
c.add(Calendar.YEAR, 56);
c.add(Calendar.MONTH, 8);
c.getTime();
System.out.println(sdf.format(c.getTime()));
}
}
When you are parsing a BS String using SimpleDateFormat, it may give parse exception as BS months don't have a same number of dates as AD. Some times a BS month can have 32 days, as anexample, 32-02-2070 is not a valid string. As long as the calculation of number of days in a BS month is implemented in program, I don't think it is possible without any error.