converting date format - java

I got date as '14-Dec-2010' i want to get the month in number format for the given date.
that is., i want to convert the date to '14-12-2010'.

DateFormat inFm = new SimpleDateFormat("d-MMM-y");
DateFormat outFm = new SimpleDateFormat("d-M-yyyy");
Date date = inFm.parse("14-Dec-2010");
String output = outFm.format(date);
Generally, you should use a datetime type like Date internally, then transform to String at output time.

import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatter {
/**
* #param args
*/
public static void main(String[] args) {
Date date = new Date("14-Dec-2010"); //deprecated. change it to your needs
DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(df.format(date));
}
}

I think this SQL convert should work
SELECT CONVERT(datetime,'14-Dec-2010',105)

DateFormat format = new SimpleDateFormat("dd-MMM-yyyy");
Date date= format.parse("14-Dec-2010");
This is how you will get Date Object now you can print it in any format.
Note: month starts from 0 , so for Dec it would be 11
Here is working IDE One demo
Document

Avoid using the troublesome old date-time classes bundled with the earliest versions of Java. They are poorly designed and confusing.
java.time
The old classes are supplanted by the java.time framework.
For a date-only value without time of day and without time zone use LocalDate class.
Parse the String input using DateTimeFormatter.
String input = "14-Dec-2010";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd-MMM-yyyy" );
LocalDate localDate = LocalDate.parse( input , formatter );
To generate a String in another format, define another formatter.
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern( "dd-MM-yyyy" );
String output = localDate.format( formatter2 );
Better yet, let DateTimeFormatter automatically localize.
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ).withLocale( l );
String output = localDate.format( f ); // Generates String in a localized format.
SQL
For SQL just pass objects, do not use strings. Pass LocalDate via setObject on a PreparedStatement if your JDBC driver complies with the JDBC 4.2 spec.
myPrepStmt.setObject( localDate );
If not, fall back to the old java.sql.Date class by using new conversion methods added to the old classes.
java.sql.Date sqlDate = java.sql.Date.from( localDate );
myPrepStmt.setDate( sqlDate );

Related

Convert date format from string

I have a string where contain date and time with format like this
"2020-09-20-08-40"
i try to convert that string to date with format "dd-MM-yyyy HH:mm" and print that in a textview. I saw other people try convert with this way
String dateString = "2020-09-20-08-40"
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date = format1.parse(dateString);
String dateFinal = format2.format(date);
t_date.setText(dateFinal);
when i try this way, i got error java.lang.IllegalArgumentException
How to solve this?
tl;dr
LocalDateTime.parse(
"2020-09-20-08-40" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" )
)
See code run live at IdeOne.com.
2020-09-20T08:40
Details
Avoid using terrible legacy date-time classes. Use only java.time classes.
Define a formatting pattern to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd-HH-mm" ) ;
Parse your input text.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Tip: Educate the publisher of your data about the ISO 8601 standard for exchanging date-time values as text. No need to be inventing such formats as seen in your Question. The java.time classes use the standard formats by default when parsing/generating strings, so no need to specify a formatting pattern.
Thanks to #Nima Khalili and #Andre Artus answer, i can solve this. My code will look this
String dateString = "2020-09-20-08-40"
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd-HH-mm");
format1.setTimeZone(TimeZone.getTimeZone("GMT + 7"));
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy HH:mm");
Date date;
try {
date = format1.parse(dateString);
String dateFinal = format2.format(date);
t_date.setText(dateFinal);
} catch (ParseException e) {
e.printStackTrace();
}
If you have a date+time like "2020-09-20-08-40" then your format should reflect that, e.g.
"yyyy-MM-dd-HH-mm"

JAVA 8 Timestamp- Cant we change the format of timestamp in the way we want?

No matter what I do its not working. I want to have it in dd/mm/yyyy I have tried and unable to get it done.Tried with JAVA 8 api of Instant localdate localtime localdatetime too.
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = dateFormat.parse("23/09/2007");
long time = date.getTime();
Timestamp ts = new Timestamp(time);
System.out.println(ts);
Prints like this 2007-09-23 00:00:00.0;
TimeStamp has its own format, so you need to format it as per your needs
Try,
SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = f.parse("23/12/2007 00:00:00");
String strDate = f.format(date);
System.out.println("Current Date = "+strDate);
java.time
You are using terrible date-time classes that were years ago supplanted by the modern java.time classes.
➥ Never use java.util.Date, java.sql.Date, nor java.sql.Timestamp.
For a date only, without time-of-day and without time zone, use LocalDate.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu" ) ;
String input = "23/09/2007" ;
LocalDate ld = LocalDate.parse( input , f ) ;
Generate text in standard ISO 8601 format.
String output = ld.toString() ;
Generate text in that same custom format.
String output = ld.format( f ) ;

converting UTC date string to local date string inspecific format

I have a UTC date in string
String utcDate = "2014-03-05 07:09:07.0";
I want to convert it to local date string of format DD-MMM-YYYY hh:mm a
eg: 5-Mar-2014 12:39 PM from UTC date 2014-03-05 07:09:07.0
How this can be achieved using simple java or joda API
Very easy to achieve with default functionality. I hope the local data is for display only.
SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S");
parser.setTimeZone(TimeZone.getTimeZone("UTC"));
Date parsed = parser.parse(utcDate);
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM-yyyy hh:mm a");
System.out.println(formatter.format(parsed));
The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Instead use either Joda-Time library or the new java.time package in bundled with Java 8.
If you use the ISO 8601 format of strings, you can pass the string directly to a Joda-Time DateTime constructor. Your input string is close, but the space in the middle should be a T.
Some example code using the Joda-Time 2.3 library.
String input = "2014-03-05 07:09:07.0";
String inputModified = input.replace( " ", "T" );
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );
DateTime dateTimeUtc = new DateTime( inputModified, DateTimeZone.UTC );
DateTime dateTimeParis = dateTimeUTC.toZone( timeZone );
String outputFrance = DateTimeFormat.forPattern( "FF" ).withLocale(Locale.FRANCE).print( dateTimeParis );
DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-MMM-yyyy hh:mm a" ).withLocale( Locale.US );
String outputParisCustom = formatter.print( dateTimeParis );
Below code will help you to convert your UTC to IST or any other timezone. You need to pay attention to the timezone that you want to use with SimpleDateFormat.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class ConvertTimeZone {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = sdf.parse("2014-03-05 07:09:07");
System.out.println("time in UTC " +sdf.format(date));
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println("Time in IST is " + sdf.format(date));
}
}

How can I change the date format in Java? [duplicate]

This question already has answers here:
java.util.Date format conversion yyyy-mm-dd to mm-dd-yyyy
(8 answers)
Closed 3 years ago.
I need to change the date format using Java from
dd/MM/yyyy to yyyy/MM/dd
How to convert from one date format to another using SimpleDateFormat:
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
SimpleDateFormat sdf = new SimpleDateFormat(OLD_FORMAT);
Date d = sdf.parse(oldDateString);
sdf.applyPattern(NEW_FORMAT);
newDateString = sdf.format(d);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
sdf.format(new Date());
This should do the trick
tl;dr
LocalDate.parse(
"23/01/2017" ,
DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK )
).format(
DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK )
)
2017/01/23
Avoid legacy date-time classes
The answer by Christopher Parker is correct but outdated. The troublesome old date-time classes such as java.util.Date, java.util.Calendar, and java.text.SimpleTextFormat are now legacy, supplanted by the java.time classes.
Using java.time
Parse the input string as a date-time object, then generate a new String object in the desired format.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter fIn = DateTimeFormatter.ofPattern( "dd/MM/uuuu" , Locale.UK ); // As a habit, specify the desired/expected locale, though in this case the locale is irrelevant.
LocalDate ld = LocalDate.parse( "23/01/2017" , fIn );
Define another formatter for the output.
DateTimeFormatter fOut = DateTimeFormatter.ofPattern( "uuuu/MM/dd" , Locale.UK );
String output = ld.format( fOut );
2017/01/23
By the way, consider using standard ISO 8601 formats for strings representing date-time values.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Joda-Time
UPDATE: The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. This section here is left for the sake of history.
For fun, here is his code adapted for using the Joda-Time library.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
final String OLD_FORMAT = "dd/MM/yyyy";
final String NEW_FORMAT = "yyyy/MM/dd";
// August 12, 2010
String oldDateString = "12/08/2010";
String newDateString;
DateTimeFormatter formatterOld = DateTimeFormat.forPattern(OLD_FORMAT);
DateTimeFormatter formatterNew = DateTimeFormat.forPattern(NEW_FORMAT);
LocalDate localDate = formatterOld.parseLocalDate( oldDateString );
newDateString = formatterNew.print( localDate );
Dump to console…
System.out.println( "localDate: " + localDate );
System.out.println( "newDateString: " + newDateString );
When run…
localDate: 2010-08-12
newDateString: 2010/08/12
Use SimpleDateFormat
String DATE_FORMAT = "yyyy/MM/dd";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Formated Date " + sdf.format(date));
Complete Example:
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaSimpleDateFormatExample {
public static void main(String args[]) {
// Create Date object.
Date date = new Date();
// Specify the desired date format
String DATE_FORMAT = "yyyy/MM/dd";
// Create object of SimpleDateFormat and pass the desired date format.
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
/*
* Use format method of SimpleDateFormat class to format the date.
*/
System.out.println("Today is " + sdf.format(date));
}
}
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date myDate = sdf.parse("28/12/2013");
sdf.applyPattern("yyyy/MM/dd")
String myDateString = sdf.format(myDate);
Now myDateString = 2013/12/28
This is just Christopher Parker's answer adapted to use the new1 classes from Java 8:
final DateTimeFormatter OLD_FORMATTER = DateTimeFormatter.ofPattern("dd/MM/yyyy");
final DateTimeFormatter NEW_FORMATTER = DateTimeFormatter.ofPattern("yyyy/MM/dd");
String oldString = "26/07/2017";
LocalDate date = LocalDate.parse(oldString, OLD_FORMATTER);
String newString = date.format(NEW_FORMATTER);
1 well, not that new anymore, Java 9 should be released soon.
Or you could go the regex route:
String date = "10/07/2010";
String newDate = date.replaceAll("(\\d+)/(\\d+)/(\\d+)", "$3/$2/$1");
System.out.println(newDate);
It works both ways too. Of course this won't actually validate your date and will also work for strings like "21432/32423/52352". You can use "(\\d{2})/(\\d{2})/(\\d{4}" to be more exact in the number of digits in each group, but it will only work from dd/MM/yyyy to yyyy/MM/dd and not the other way around anymore (and still accepts invalid numbers in there like 45). And if you give it something invalid like "blabla" it will just return the same thing back.
many ways to change date format
private final String dateTimeFormatPattern = "yyyy/MM/dd";
private final Date now = new Date();
final DateFormat format = new SimpleDateFormat(dateTimeFormatPattern);
final String nowString = format.format(now);
final Instant instant = now.toInstant();
final DateTimeFormatter formatter =
DateTimeFormatter.ofPattern(
dateTimeFormatPattern).withZone(ZoneId.systemDefault());
final String formattedInstance = formatter.format(instant);
/* Java 8 needed*/
LocalDate date = LocalDate.now();
String text = date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text, formatter);
To Change the format of Date you have Require both format look below.
String stringdate1 = "28/04/2010";
try {
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy");
Date date1 = format1.parse()
SimpleDateFormat format2 = new SimpleDateFormat("yyyy/MM/dd");
String stringdate2 = format2.format(date1);
} catch (ParseException e) {
e.printStackTrace();
}
here stringdate2 have date format of yyyy/MM/dd. and it contain 2010/04/28.
SimpleDateFormat format1 = new SimpleDateFormat("yyyy/MM/dd");
System.out.println(format1.format(date));

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

The code below gives me the current time. But it does not tell anything about milliseconds.
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
I have a date in the format YYYY-MM-DD HH:MM:SS (2009-09-22 16:47:08).
But I want to retrieve the current time in the format YYYY-MM-DD HH:MM:SS.MS (2009-09-22 16:47:08.128, where 128 are the milliseconds).
SimpleTextFormat will work fine. Here the lowest unit of time is second, but how do I get millisecond as well?
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
A Java one liner
public String getCurrentTimeStamp() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
}
in JDK8 style
public String getCurrentLocalDateTimeStamp() {
return LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
}
You only have to add the millisecond field in your date format string:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The API doc of SimpleDateFormat describes the format string in detail.
try this:-
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
Date date = new Date();
System.out.println(dateFormat.format(date));
or
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
tl;dr
Instant.now()
.toString()
2016-05-06T23:24:25.694Z
ZonedDateTime
.now
(
ZoneId.of( "America/Montreal" )
)
.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
.replace( "T" , " " )
2016-05-06 19:24:25.694
java.time
In Java 8 and later, we have the java.time framework built into Java 8 and later. These new classes supplant the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extra project. See the Tutorial.
Be aware that java.time is capable of nanosecond resolution (9 decimal places in fraction of second), versus the millisecond resolution (3 decimal places) of both java.util.Date & Joda-Time. So when formatting to display only 3 decimal places, you could be hiding data.
If you want to eliminate any microseconds or nanoseconds from your data, truncate.
Instant instant2 = instant.truncatedTo( ChronoUnit.MILLIS ) ;
The java.time classes use ISO 8601 format by default when parsing/generating strings. A Z at the end is short for Zulu, and means UTC.
An Instant represents a moment on the timeline in UTC with resolution of up to nanoseconds. Capturing the current moment in Java 8 is limited to milliseconds, with a new implementation in Java 9 capturing up to nanoseconds depending on your computer’s hardware clock’s abilities.
Instant instant = Instant.now (); // Current date-time in UTC.
String output = instant.toString ();
2016-05-06T23:24:25.694Z
Replace the T in the middle with a space, and the Z with nothing, to get your desired output.
String output = instant.toString ().replace ( "T" , " " ).replace( "Z" , "" ; // Replace 'T', delete 'Z'. I recommend leaving the `Z` or any other such [offset-from-UTC][7] or [time zone][7] indicator to make the meaning clear, but your choice of course.
2016-05-06 23:24:25.694
As you don't care about including the offset or time zone, make a "local" date-time unrelated to any particular locality.
String output = LocalDateTime.now ( ).toString ().replace ( "T", " " );
Joda-Time
The highly successful Joda-Time library was the inspiration for the java.time framework. Advisable to migrate to java.time when convenient.
The ISO 8601 format includes milliseconds, and is the default for the Joda-Time 2.4 library.
System.out.println( "Now: " + new DateTime ( DateTimeZone.UTC ) );
When run…
Now: 2013-11-26T20:25:12.014Z
Also, you can ask for the milliseconds fraction-of-a-second as a number, if needed:
int millisOfSecond = myDateTime.getMillisOfSecond ();
The easiest way was to (prior to Java 8) use,
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
But SimpleDateFormat is not thread-safe. Neither java.util.Date. This will lead to leading to potential concurrency issues for users. And there are many problems in those existing designs. To overcome these now in Java 8 we have a separate package called java.time. This Java SE 8 Date and Time document has a good overview about it.
So in Java 8 something like below will do the trick (to format the current date/time),
LocalDateTime.now()
.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
And one thing to note is it was developed with the help of the popular third party library joda-time,
The project has been led jointly by the author of Joda-Time (Stephen Colebourne) and Oracle, under JSR 310, and will appear in the new Java SE 8 package java.time.
But now the joda-time is becoming deprecated and asked the users to migrate to new java.time.
Note that from Java SE 8 onwards, users are asked to migrate to java.time (JSR-310) - a core part of the JDK which replaces this project
Anyway having said that,
If you have a Calendar instance you can use below to convert it to the new java.time,
Calendar calendar = Calendar.getInstance();
long longValue = calendar.getTimeInMillis();
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue), ZoneId.systemDefault());
String formattedString = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(date.toString()); // 2018-03-06T15:56:53.634
System.out.println(formattedString); // 2018-03-06 15:56:53.634
If you had a Date object,
Date date = new Date();
long longValue2 = date.getTime();
LocalDateTime dateTime =
LocalDateTime.ofInstant(Instant.ofEpochMilli(longValue2), ZoneId.systemDefault());
String formattedString = dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"));
System.out.println(dateTime.toString()); // 2018-03-06T15:59:30.278
System.out.println(formattedString); // 2018-03-06 15:59:30.278
If you just had the epoch milliseconds,
LocalDateTime date =
LocalDateTime.ofInstant(Instant.ofEpochMilli(epochLongValue), ZoneId.systemDefault());
I would use something like this:
String.format("%tF %<tT.%<tL", dateTime);
Variable dateTime could be any date and/or time value, see JavaDoc for Formatter.
I have a simple example here to display date and time with Millisecond......
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class MyClass{
public static void main(String[]args){
LocalDateTime myObj = LocalDateTime.now();
DateTimeFormatter myFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
String forDate = myObj.format(myFormat);
System.out.println("The Date and Time are: " + forDate);
}
}
To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.
import java.text.SimpleDateFormat;
import java.util.Date;
public class test {
public static void main(String argv[]){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date now = new Date();
String strDate = sdf.format(now);
System.out.println(strDate);
}
}
Use this to get your current time in specified format :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(dateFormat.format(System.currentTimeMillis())); }
java.time
The question and the accepted answer use java.util.Date and SimpleDateFormat which was the correct thing to do in 2009. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.
Solution using java.time, the modern date-time API:
LocalDateTime.now(ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS"))
Some important points about this solution:
Replace ZoneId.systemDefault() with the applicable ZoneId e.g. ZoneId.of("America/New_York").
If the current date-time is required in the system's default timezone (ZoneId), you do not need to use LocalDateTime#now(ZoneId zone); instead, you can use LocalDateTime#now().
You can use y instead of u here but I prefer u to y.
Demo:
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
class Main {
public static void main(String args[]) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss.SSS", Locale.ENGLISH);
// Replace ZoneId.systemDefault() with the applicable ZoneId e.g.
// ZoneId.of("America/New_York")
LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
String formattedDateTimeStr = ldt.format(formatter);
System.out.println(formattedDateTimeStr);
}
}
Output from a sample run in my system's timezone, Europe/London:
2023-01-02 09:53:14.353
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
I don't see a reference to this:
SimpleDateFormat f = new SimpleDateFormat("yyyyMMddHHmmssSSS");
above format is also useful.
http://www.java2s.com/Tutorials/Java/Date/Date_Format/Format_date_in_yyyyMMddHHmmssSSS_format_in_Java.htm
Ans:
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
ZonedDateTime start = Instant.now().atZone(ZoneId.systemDefault());
String startTimestamp = start.format(dateFormatter);
java.text (prior to java 8)
public static ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
};
};
...
dateFormat.get().format(new Date());
java.time
public static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS");
...
dateTimeFormatter.format(LocalDateTime.now());
The doc in Java 8 names it fraction-of-second , while in Java 6 was named millisecond. This brought me to confusion
You can simply get it in the format you want.
String date = String.valueOf(android.text.format.DateFormat.format("dd-MM-yyyy", new java.util.Date()));

Categories

Resources