My json respons contains a CreatedOn Date:
{
"CreatedOn" : "\/Date(1406192939581)\/"
}
I need to convert CreatedOn to a simple date format and count the days of difference from CreatedOn Date to Present Date.
When I debug the below code string CreatedOn showing a null value. How come?
JSONObject store = new JSONObject(response);
if (response.contains("CreatedOn"))
{
String CreatedOn = store.getString("CreatedOn");
}
JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Timestamp stamp = new Timestamp(store.getLong("CreatedOn"));
Date date = new Date(stamp.getTime());
System.out.println(date);
}
or
JSONObject store = new JSONObject(response);
if(store.has("CreatedOn")) {
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
Date date = new Date(datetimestamp);
DateFormat formatter = new SimpleDateFormat("HH:mm:ss:SSS");
String dateFormatted = formatter.format(date);
}
consider using JSON methods instead of contains. JSON has "has()" which validate if key exists.
You should also make sure that you try {} catch {} the String first, to make sure its valid JSON.
Update:
Your Value is
/Date(1406192939581)/
which means it must be formatted first.
Get it by parsing the string with
Integer datetimestamp = Integer.parseInt(store.getString("CreatedOn").replaceAll("\\D", ""));
java.time
It’s about time that someone provides the modern answer. When this question was asked in 2014, Java 8 had just come out, and with it java.time, the modern Java date and time API. Today I recommend we all use this and avoid the old classes Timestamp, Date, DateFormat and SimpleDateFormat used in the other answer. The old classes were poorly designed and were replaced for a good reason.
Edit: With Java 8 you can directly parse your string from JSON into an Instant using an advanced formatter, which I consider quite elegant:
DateTimeFormatter jsonDateFormatter = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendLiteral(")/")
.toFormatter();
String createdOn = "/Date(1406192939581)/";
Instant created = jsonDateFormatter.parse(createdOn, Instant::from);
System.out.println("Created on " + created);
Output from this snippet is:
Created on 2014-07-24T09:08:59.581Z
The formatter knows that the last 3 digits are milliseconds of the second and considers all the preceding digits seconds since the epoch, so this works the way it should. To count the days of difference from CreatedOn Date to Present Date:
ZoneId zone = ZoneId.of("Antarctica/South_Pole");
long days = ChronoUnit.DAYS.between(created.atZone(zone).toLocalDate(), LocalDate.now(zone));
System.out.println("Days of difference: " + days);
Output today (2019-12-20):
Days of difference: 1975
Please substitute your desired time zone if it didn’t happen to be Antarctica/South_Pole.
Original answer:
final Pattern jsonDatePattern = Pattern.compile("/Date\\((\\d+)\\)/");
String createdOn = "/Date(1406192939581)/";
Matcher dateMatcher = jsonDatePattern.matcher(createdOn);
if (dateMatcher.matches()) {
Instant created = Instant.ofEpochMilli(Long.parseLong(dateMatcher.group(1)));
System.out.println("Created on " + created);
} else {
System.err.println("Invalid format: " + createdOn);
}
Output is:
Created on 2014-07-24T09:08:59.581Z
I am using a regular expression not only to extract the number from the string, but also for validation of the string.
The modern Instant class represents a point in time. It’s toString method renders the time in UTC, so this is what you see in the output, denoted by the trailing Z.
Link: Oracle tutorial: Date Time explaining how to use java.time.
java.time
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Instant#ofEpochMilli
The key here is to get an object of Instant out of the milliseconds in the JSON string. Once you have Instant, you can convert it to other java.time types e.g. ZonedDateTime or even to the legacy java.util.Date.
A note on the regex, \D+: \D specifies a non-digit while + specifies its one or more occurrence(s).
Demo:
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
JSONObject store = new JSONObject("{\n" + "\"CreatedOn\" : \"\\/Date(1406192939581)\\/\"\n" + "}");
if (store.has("CreatedOn")) {
// Replace all non-digits i.e. \D+ with a blank string
Instant instant = Instant.ofEpochMilli(Long.parseLong(store.getString("CreatedOn").replaceAll("\\D+", "")));
System.out.println(instant);
// Now you can convert Instant to other java.time types e.g. ZonedDateTime
// ZoneId.systemDefault() returns the time-zone of the JVM. Replace it with the
// desired time-zone e.g. ZoneId.of("Europe/London")
ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
// Print the default format i.e. the value of zdt#toString
System.out.println(zdt);
// A custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMMM dd HH:mm:ss uuuu", Locale.ENGLISH);
String strDateTimeFormatted = zdt.format(dtf);
System.out.println(strDateTimeFormatted);
}
}
}
Output:
2014-07-24T09:08:59.581Z
2014-07-24T10:08:59.581+01:00[Europe/London]
Thu July 24 10:08:59 2014
Learn more about the modern date-time API from Trail: Date Time.
How to get java.util.Date from an Instant:
You should avoid using java.util.Date but for whatsoever purpose, if you want to get java.util.Date, all you have to do is to use Date#from as shown below:
Date date = Date.from(instant);
Related
I'm getting this date from bing search and have difficulty to parse it to date, I need
the time as well.
""2021-09-02T13:16:00.0000000Z""
I'm doing this:
public static Date parseDate(String publishedDate) {
String dateStr = publishedDate.replaceFirst("T", "");
SimpleDateFormat formatter = null;
if (publishedDate.length() > 10) {
formatter = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss");
} else {
formatter = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = null;
try {
date = formatter.parse(publishedDate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
getting the following error:
java.text.ParseException: Unparseable date: ""2021-09-02T13:16:00.0000000Z""
at java.base/java.text.DateFormat.parse(DateFormat.java:396)
Parse the quotes too; use java.time.Instant
Like many others I recommend that you use java.time, the modern Java date and time API, for your date and time work.
Your string contains double quotes first and last. You can deal with them in two ways:
If there’s a way that you can get your string from Bing search without the quotes, do that. Then Instant.parse() will parse your string, and you’re done.
Otherwise java.time can parse the quotes too.
For parsing the quotes use the following formatter:
private static final DateTimeFormatter BING_INSTANT_PARSER
= new DateTimeFormatterBuilder().appendLiteral('"')
.append(DateTimeFormatter.ISO_INSTANT)
.appendLiteral('"')
.toFormatter();
Then parse like this:
String stringFromBing = "\"2021-09-02T13:16:00.0000000Z\"";
Instant instant = BING_INSTANT_PARSER.parse(stringFromBing, Instant::from);
System.out.println("String to parse: " + stringFromBing);
System.out.println("Result: " + instant);
Output:
String to parse: "2021-09-02T13:16:00.0000000Z"
Result: 2021-09-02T13:16:00Z
Which java.time class to use?
Assuming that your string always comes with the Z at the end, denoting UTC, Instant is the correct class to use. OffsetDateTime and ZonedDateTime will work too, but I consider them overkill. You don’t want to use LocalDateTime since you would then throw away the essential information that the string is in UTC.
Link
Oracle tutorial: Date Time explaining how to use java.time.
What you are dealing with is called Time Stamp,
there are Duration and INSTANT classes to deal with it.
This page explain it all
https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
As #Basil Bourque suggested, we dont need DateTimeFormatter because Instant.parse() by default uses UTC. Also, we can use OffsetDateTime instead of ZonedDateTime (more detailed),
String date = "2021-09-02T13:16:00.0000000Z";
Instant timeStamp = Instant.parse(date);
// To get Time or Date," with Instant you must provide time-zone too"
ZonedDateTime dateTimeZone = ZonedDateTime.ofInstant(timeStamp, ZoneOffset.UTC);
System.out.println(dateTimeZone);
System.out.println(dateTimeZone.toLocalDate());// can also be tolocalTime
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT 2010". But I expected to get the date in the following format "yyyy-MM-dd HH:mm". What's wrong in this code?
String date = "2010-08-25";
String time = "00:00";
Also in one laptop the output for,e.g. 23:45 is 11:45. How can I define exactly the 24 format?
private static Date date(final String date,final String time) {
final Calendar calendar = Calendar.getInstance();
String[] ymd = date.split("-");
int year = Integer.parseInt(ymd[0]);
int month = Integer.parseInt(ymd[1]);
int day = Integer.parseInt(ymd[2]);
String[] hm = time.split(":");
int hour = Integer.parseInt(hm[0]);
int minute = Integer.parseInt(hm[1]);
calendar.set(Calendar.YEAR,year);
calendar.set(Calendar.MONTH,month);
calendar.set(Calendar.DAY_OF_MONTH,day);
calendar.set(Calendar.HOUR,hour);
calendar.set(Calendar.MINUTE,minute);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date d = calendar.getTime();
String dateString= dateFormat.format(d);
Date result = null;
try {
result = (Date)dateFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
return result;
}
What's wrong in this code?
You seem to be expecting the returned Date object to know about the format you've parsed it from - it doesn't. It's just an instant in time. When you want a date in a particular format, you use SimpleDateFormat.format, it's as simple as that. (Well, or you use a better library such as Joda Time.)
Think of the Date value as being like an int - an int is just a number; you don't have "an int in hex" or "an int in decimal"... you make that decision when you want to format it. The same is true with Date.
(Likewise a Date isn't associated with a specific calendar, time zone or locale. It's just an instant in time.)
How did you print out the return result? If you simply use System.out.println(date("2010-08-25", "00:00") then you might get Sat Sep 8 00:00 PDT 2010 depending on your current date time format setting in your running machine. But well what you can do is:
Date d = date("2010-08-25", "00:00");
System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(d));
Just curious why do you bother with this whole process as you can simple get the result by concatenate your initial date and time string.
just use SimpleDateFormat class
See
date formatting java simpledateformat
The standard library does not support a formatted Date-Time object.
The function shown below returns the date, e.g. "Sat Sep 8 00:00 PDT
2010". But I expected to get the date in the following format
"yyyy-MM-dd HH:mm".
The standard Date-Time classes do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String using a Date-Time parsing/formatting type:
For the modern Date-Time API: java.time.format.DateTimeFormatter
For the legacy Date-Time API: java.text.SimpleDateFormat
About java.util.Date:
A java.util.Date object simply represents the number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT (or UTC). Since it does not hold any timezone information, its toString function applies the JVM's timezone to return a String in the format, EEE MMM dd HH:mm:ss zzz yyyy, derived from this milliseconds value. To get the String representation of the java.util.Date object in a different format and timezone, you need to use SimpleDateFormat with the desired format and the applicable timezone e.g.
Date date = new Date(); // In your case, it will be Date date = date("2010-08-25", "00:00");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
// sdf.setTimeZone(TimeZone.getTimeZone("America/New_York")); // For a timezone-specific value
String strDate = sdf.format(date);
System.out.println(strDate);
Your function, Date date(String, String) is error-prone.
You can simply combine the date and time string with a separator and then use SimpleDateFormat to parse the combined string e.g. you can combine them with a whitespace character as the separator to use the same SimpleDateFormat shown above.
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
Note that using a separator is not a mandatory requirement e.g. you can do it as sdf.parse(date + time) but for this, you need to change the format of sdf to yyyy-MM-ddHH:mm which, although correct, may look confusing.
Demo:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.ENGLISH);
public static void main(String[] args) throws ParseException {
Date date = date("2010-08-25", "00:00");
String strDate = sdf.format(date);
System.out.println(strDate);
}
private static Date date(final String date, final String time) throws ParseException {
return sdf.parse(date + " " + time);
}
}
Output:
2010-08-25 00:00
ONLINE DEMO
Switch to java.time API.
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
LocalDateTime ldt = localDateTime("2010-08-25", "00:00");
// Default format i.e. the value of ldt.toString()
System.out.println(ldt);
// Custom format
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm", Locale.ENGLISH);
String strDate = dtf.format(ldt);
System.out.println(strDate);
}
private static LocalDateTime localDateTime(final String date, final String time) {
return LocalDateTime.of(LocalDate.parse(date), LocalTime.parse(time));
}
}
Output:
2010-08-25T00:00
2010-08-25 00:00
ONLINE DEMO
You must have noticed that I have not used DateTimeFormatter for parsing the String date and String time. It is because your date and time strings conform to the ISO 8601 standards. The modern Date-Time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the Date-Time string conforms to the ISO 8601 standards.
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
I'm surprise you are getting different date outputs on the different computers. In theory, SimpleDateFormat pattern "H" is supposed to output the date in a 24h format. Do you get 11:45pm or 11:45am?
Although it should not affect the result, SimpleDateFormat and Calendar are Locale dependent, so you can try to specify the exact locale that you want to use (Locale.US) and see if that makes any difference.
As a final suggestion, if you want, you can also try to use the Joda-Time library (DateTime) to do the date manipulation instead. It makes it significantly easier working with date objects.
DateTime date = new DateTime( 1991, 10, 13, 23, 39, 0);
String dateString = new SimpleDateFormat("yyyy-MM-dd HH:mm").format( date.toDate());
DateTime newDate = DateTime.parse( dateString, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm"));
I am getting a date string as 2014-01-11-T00:00:00Z
I want to convert this date to 20140111 i.e YYYYMMDD it should be a string.
Any standard method/function to achieve above?
java.time
Your date-time string, 2014-01-11-T00:00:00Z is a bit weird as I have never seen such a date-time string where there is a hyphen (-) before T. For this kind of string, the following pattern meets the parsing requirement:
yyyy-M-d-'T'H:m:sXXX
Also, with java.time API, I recommend you replace y with u as explained in this answer. For the output string, you do NOT need to define any pattern as there already exists an inbuilt DateTimeFormatter for this pattern: DateTimeFormatter.BASIC_ISO_DATE.
Demo:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String args[]) {
DateTimeFormatter dtfInput = DateTimeFormatter.ofPattern("u-M-d-'T'H:m:sXXX", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse("2014-01-11-T00:00:00Z", dtfInput);
System.out.println(odt);
String output = odt.toLocalDate().format(DateTimeFormatter.BASIC_ISO_DATE);
System.out.println(output);
}
}
Output:
2014-01-11T00:00Z
20140111
Note:
Had your date-time string been ISO 8601 compliant, you would NOT have needed to use a DateTimeFormatter object explicitly for parsing i.e. you could have simply parsed it as
OffsetDateTime odt = OffsetDateTime.parse("2014-01-11T00:00:00Z");
The Z in the date-time stands for Zulu which specifies UTC time (that has a timezone offset of +00:00 hours) in ISO 8601 standard. Thus, this solution will also work for a date-time string like 2014-01-11-T00:00:00+02:00 which has a timezone offset of +02:00 hours.
In case, you need a java.util.Date object from this object of OffsetDateTime, you can do so as follows:
Date date = Date.from(odt.toInstant());
Learn more about the the modern date-time API* from Trail: Date Time.
Note that the legacy date-time API (java.util date-time types and their formatting API, SimpleDateFormat) are outdated and error-prone. It is recommended to stop using them completely and switch to java.time API. Just for the sake of completeness, I am providing you with a solution using the legacy API.
Using the legacy API:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class Main {
public static void main(String args[]) throws ParseException {
SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-M-d-'T'H:m:sXXX", Locale.ENGLISH);
SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
sdfOutput.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));// Change it as required
Date date = sdfInput.parse("2014-01-11-T00:00:00Z");
String output = sdfOutput.format(date);
System.out.println(output);
}
}
Output:
20140111
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Take this
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) throws ParseException {
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd-'T'HH:mm:ss'Z'");
Date inDate = inFormat.parse("2014-01-11-T00:00:00Z");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
String output = outFormat.format(inDate);
System.out.println("Date: " + output);
}
}
Take a look at this thread for Date formatting in Java using Zoulou notation :
Converting ISO 8601-compliant String to java.util.Date
Then create a new SimpleDateFormat using the "yyyyMMdd" format string.
Here an improved version of given answer by #drkunibar:
SimpleDateFormat inFormat = new SimpleDateFormat("yyyy-MM-dd-'T'HH:mm:ss'Z'");
inFormat.setTimeZone(TimeZone.getTimeZone("GMT")); // Z denotes UTC in ISO-8601
Date inDate = inFormat.parse("2014-01-11-T00:00:00Z");
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMdd");
outFormat.setTimeZone(TimeZone.getTimeZone("...")); // set your timezone explicitly!
String output = outFormat.format(inDate);
System.out.println("Date: " + output);
Note that the format YYYYMMDD is also ISO-8601-compliant (a so-called basic calendar date). The question you have to ask yourself is in which timezone you want to get your output. If in UTC you have to set "GMT", too. Without setting timezone it can happen that your output date differs from input UTC date by one day dependent where your default system timezone is (for example US is several hours behind UTC, in this case one calendar day before UTC midnight).
Update: This Answer is now obsolete. See the modern solution using java.time in the Answer by Avinash.
Joda-Time
This date-time work is much easier with the Joda-Time 2.3 library.
String input = "2014-01-11T00:00:00Z"; // In standard ISO 8601 format.
DateTime dateTime = new DateTime( input, DateTimeZone.UTC ); // Parse string into date-time object.
DateTimeFormatter formatter = ISODateTimeFormat.basicDate(); // Factory to make a formatter.
String output = formatter.print( dateTime ); // Generate string from date-Time object.
there are two string
String date = "9/13/2012";
String time = "5:48pm";
the time is GMT+0, I wanna change it to GMT+8,what is the simplest way to change a time to particular timezone
Parse it using a SimpleDateFormat set to the UTC time zone
Format the parsed Date value using a SimpleDateFormat set to the time zone you're interested in. (It's likely to be something other than just "UTC+8" - you should find out which TZDB time zone ID you really want.
For example:
SimpleDateFormat inputFormat = new SimpleDateFormat("MM/dd/yyyy h:mma", Locale.US);
inputFormat.setTimeZone(TimeZone.getTimeZone("Etc/UTC");
Date date = inputFormat.parse(date + " " + time);
// Or whatever format you want...
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.US);
outputFormat.setTimeZone(targetTimeZone);
String outputText = outputFormat.format(date);
(If you can use Joda Time instead, that'd be great - but I understand that it's pretty big for an Android app.)
The Joda-Time library provides a good set of objects for working with dates/times in multiple time zones. http://joda-time.sourceforge.net/
Something like this for example:
String date = "9/13/2012";
String time = "5:48pm";
String[] dateParts = date.split("/");
Integer month = Integer.parseInt(dateParts[0]);
Integer day = Integer.parseInt(dateParts[1]);
Integer year = Integer.parseInt(dateParts[2]);
String[] timeParts = time.split(":");
Integer hour = Integer.parseInt(timeParts[0]);
Integer minutes = Integer.parseInt(timeParts[1].substring(0,timeParts[1].lastIndexOf("p")));
DateTime dateTime = new DateTime(year, month, day, hour, minutes, DateTimeZone.forID("Etc/GMT"));
dateTime.withZone(DateTimeZone.forID("Etc/GMT+8"));
java.time
The java.util Date-Time API and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern Date-Time API*.
Also, quoted below is a notice from the home page of Joda-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.
Solution using java.time, the modern Date-Time API:
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String date = "9/13/2012";
String time = "5:48pm";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("M/d/u h:ma", Locale.UK);
LocalDateTime ldtSource = LocalDateTime.parse(date + " " + time, dtf);
OffsetDateTime odtSource = ldtSource.atOffset(ZoneOffset.UTC);
OffsetDateTime odtTarget = odtSource.withOffsetSameInstant(ZoneOffset.of("+08:00"));
System.out.println(odtTarget);
// In a custom format
System.out.println(odtTarget.format(dtf));
}
}
Output:
2012-09-14T01:48+08:00
9/14/2012 1:48am
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
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()));