I have a date in this format - 01 May 2020, and I want to parse it in the following format - 2020-05-01T00:00:00. I am using the following code -
static String convertDateStringFormat(String dateString, String originalDateFormat, String outputDateFormat){
DateFormat inputFormat = new SimpleDateFormat(originalDateFormat, Locale.ENGLISH);
Date input = null;
try {
input = inputFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
DateFormat outputFormat = new SimpleDateFormat(outputDateFormat, Locale.ENGLISH);
return outputFormat.format(input);
}
and I am passing the arguments as - convertDateStringFormat("01 May 2020", "dd MMM yyyy", "yyyy-MM-dd'T'HH:mm:ss"). I dont know what I am doing wrong but it gives me this exception - java.lang.IllegalArgumentException: Parse error: 2020-05-01T00:00:00, so it looks like it is converting to the right format and then throwing an exception?
Build a format using DateTimeFormatterBuilder with hour defaulted to 0 and then parse the date string into LocalDateTime.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
public class Main {
public static void main(String[] args) {
DateTimeFormatter format = new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("dd MMM yyyy"))
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.toFormatter();
String strDate = "01 May 2020";
LocalDateTime date = LocalDateTime.parse(strDate, format);
DateTimeFormatter targetFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
String strDateInTargetFormat = date.format(targetFormat);
System.out.println(strDateInTargetFormat);
}
}
Output:
2020-05-01T00:00:00
tl;dr
LocalDate
.parse(
"01 May 2020" ,
DateTimeFormatter
.ofPattern( "dd MMMM uuuu" )
.withLocale( Locale.US )
)
.atStartOfDay(
ZoneId.of( "Africa/Tunis" )
)
.format(
DateTimeFormatter.ISO_LOCAL_DATE_TIME
)
See this code run live at IdeOne.com.
2020-05-01T00:00:00
Details
You said:
I have a date in this format - 01 May 2020
That means you have text, a String, not a date. Date-time objects do not have a “format”.
Parse your text as a LocalDate.
String input = "01 May 2020" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd MMMM uuuu" ).withLocale( Locale.US ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
You said:
want to parse it in the following format - 2020-05-01T00:00:00.
No, that is not parsing. That is generating text.
But first we need to determine a time-of-day. I presume you want the first moment of the day.
Some dates in some time zones do not start at 00:00. So always let java.time determine the first moment of the day. We capture this moment as a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Amman" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
You ask for text to be generated in a format with no indication of time zone or offset-from-UTC. I recommend against this, as the reading of such text is ambiguous. But if you insist, java.time includes a predefined format for the kind of text you desire. This format is amongst those defined in ISO 8601.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;
See this code run live at IdeOne.com.
output: 2020-05-01T00:00:00
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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Use like that to convert one format to another:
DateFormat originalFormat = new SimpleDateFormat("dd MMM yyyy", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date date = originalFormat.parse("01 May 2020");
String formattedDate = targetFormat.format(date);
Related
I'm trying to parse a String that represents a Date "2017-05-22" into a Date() using SimpleDateFormat(). I also need to have the date conversion in Spanish, so I'm creating a Locale with the spanish configuration. The problem is that for some reason I still get the output in English. My phones Language & Input configuration by default is English, but I've tried to change it to Spanish as well. Here is the full code:
val localeSpanish = Locale("es", "ES")
val dateFormat = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
val dateInSpanish = dateFormat.parse("2017-01-29")
And I get this in the ouput:
Wed Jan 11 00:00:00 GMT-04:00 2017
Can someone tell me what I'm doing wrong?
As stated by others, when you are outputting dateInSpanish, you are exposing a Date instance, which is calling its toString method and its implementation constructs that string based on a static array containing the words in English
//From java.util.Date
private final static String wtb[] = {
"am", "pm",
"monday", "tuesday", "wednesday", "thursday", "friday",
"saturday", "sunday",
"january", "february", "march", "april", "may", "june",
"july", "august", "september", "october", "november", "december",
"gmt", "ut", "utc", "est", "edt", "cst", "cdt",
"mst", "mdt", "pst", "pdt"
};
When you are declaring the dateFormatter, it is meant to convert a date/string as the following example:
val dateFormatter = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
println(dateFormatter.parse("2017-01-29")) // prints: Wed Jan 29 00:00:00 GMT-02:00 2017
println(dateFormatter.format(Date()) // prints: 2018-07-27 (as today :p)
I think you should use a different mask in order to obtain the formatted string.
But if you are forced to read the date in that format, you would have to declare two formatters:
val readerFormatter = SimpleDateFormat("yyyy-MM-dd", localeSpanish)
val writerFormatter = SimpleDateFormat("d 'de' MMMM 'del' yyyy", localeSpanish)
val readDate: Date = readerFormatter.parse("2017-01-29")
val dateInSpanish: String = writerFormatter.format(readDate)
println(dateInSpanish) // prints: 29 de enero del 2017 (as today :p)
Sorry I cannot write Kotlin (yet). Can you translate form Java?
Locale localeSpanish = new Locale("es", "ES");
DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG)
.withLocale(localeSpanish);
LocalDate date = LocalDate.parse("2017-01-29");
String formattedDate = date.format(dateFormatter);
System.out.println("Fecha en español: " + formattedDate);
This prints:
Fecha en español: 29 de enero de 2017
Messages:
The date-time classes you were using, SimpleDateFormat and Date, are long outdated and poorly designed. SimpleDateFormat in particular has a reputation for being troublesome. And despite the name a Date represents a point in time, not a date. Instead use java.time, the modern Java date and time API.
For a date without time of day use the LocalDate class.
The format you are parsing, yyyy-MM-dd, is ISO 8601. The modern classes parse ISO 8601 as their default, that is, without any explicit formatter.
No matter if you use Date or LocalDate, they haven’t got neither a format nor a locale in them. They just hold the data in much the same way as an int holds a number without any format or locale. No matter if you have an int, a Date or a LocalDate, if you want a specific format, you can have that format only in a String.
To format a date for an audience in a locale, use a built-in date format. DateTimeFormatter.ofLocalizedDate gives you one, but you need to convert it to the desired locale.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
Simple, SimpleDateFormat.parse returns a Date object which is format agnostic. What you want to do is print the following:
val dateString = dateFormat.format(dateInSpanish)
Try using this for date representation and for local spanish time use your localSpanish val
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy MMM dd - HH:mm:ss",*your code here*);
String formattedDate = df.format(c.getTime());
The line:
val dateInSpanish = dateFormat.parse("2017-01-29")
does not format the date, it just extracts the date out of the string
The line:
val localeSpanish = Locale("es", "ES")
does not change your phone's configuration
so you have a date: dateInSpanish
and you can format it as you like and then print it
I have the following String that I would like to change to UTC:
Thu Aug 24 07:38:32 GMT+01:00 2017
I'm using Joda-Time library.
I know how to create a new Datetime eg new dateTime(DateTimeZone.UTC) but how can I create a DateTime object from the above String?
I have tried the following but get an exception. Surely there must be another way to create a DT obect without chopping the original String up? What if the external API changes how it sends my app the orignal String, my String manipulation code would fail.
DateTimeFormatter df = DateTimeFormat.forPattern("dd-MMM-YYYY HH:mm");
String strOrigTime = "Thu Aug 24 07:38:32 GMT+01:00 2017";
DateTime dt = DateTime.parse(strOrigTime, df);
Log.e(TAG, "dt after parse = " + dt.toString());
Error:
Caused by: java.lang.IllegalArgumentException: Invalid format: "Thu Aug 24 07:38:32 GMT+01:00 2017"
at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866)
at org.joda.time.DateTime.parse(DateTime.java:144)
The format used (dd-MMM-YYYY HH:mm) means: day (dd) followed by -, followed by month (MMM), followed by -, followed by year (YYYY) and so on (check the javadoc for more details).
This format doesn't match the input string (which has day-of-week followed by month, followed by day, then hour/minute/second, etc). So the first thing is to use a format that matches the input, otherwise you'll always get "Invalid format" errors.
Another detail is that day of week and month names are in English, so you must also use a java.util.Locale to specify the language you're using to parse the input. If you don´t use a locale, the system default will be used, and it's not guaranteed to always be English (and it can also be changed, even at runtime, so it's always better to specify one).
I also had to add "GMT" as a literal and call withOffsetParsed() to make it include the offset (+01:00) in the parsed object:
DateTimeFormatter df = DateTimeFormat
// use a pattern that matches input
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy")
// use English locale for day of week and month
.withLocale(Locale.ENGLISH)
// include the offset (+01:00) in the parsed object
.withOffsetParsed();
String strOrigTime = "Thu Aug 24 07:38:32 GMT+01:00 2017";
DateTime dt = DateTime.parse(strOrigTime, df);
System.out.println(dt.toString());
The output is:
2017-08-24T07:38:32.000+01:00
Then, you can set the UTC timezone to this object:
dt = dt.withZone(DateTimeZone.UTC);
System.out.println(dt.toString());
The output will be:
2017-08-24T06:38:32.000Z
Note that withZone method preserves the same instant (both dates represent the same point in time), just the timezone used in the output is changed. But both dates are equivalent (they represent the same instant, as 07:38 in offset +01:00 is the same as 06:38 in UTC).
If you want all dates to be converted to UTC, you can also set this in the formatter:
// set UTC to the formatter
df = df.withZone(DateTimeZone.UTC);
Then you don't need to call withZone in the DateTime objects: all parsed dates will be converted to UTC.
You also told that "if the external API changes how it sends my app the orignal String, my String manipulation code would fail".
Well, if the input String changes, you'll have to change your format as well - there's no other way, Joda-Time can't just guess what's the format, you have to tell it.
If you want to parse more than one format, there's a way to create a formatter that uses lots of different patterns and try to parse each one, until one of them works (or throw exception if none works). You could do something like that:
// format 1
DateTimeFormatter f1 = DateTimeFormat
// use a pattern that matches input
.forPattern("EEE MMM dd HH:mm:ss 'GMT'Z yyyy")
// use English locale for day of week and month
.withLocale(Locale.ENGLISH)
// include the offset (+01:00) in the parsed object
.withOffsetParsed();
// format 2
DateTimeFormatter f2 = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss Z");
// array of all possible formats
DateTimeParser[] parsers = { f1.getParser(), f2.getParser() };
// formatter that uses all the possible formats
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// append array of possible formats
.append(null, parsers)
// create formatter
.toFormatter().withLocale(Locale.ENGLISH).withOffsetParsed()
// set all parsed objects to UTC
.withZone(DateTimeZone.UTC);
// parse first format
System.out.println(DateTime.parse("Thu Aug 24 07:38:32 GMT+01:00 2017", formatter));
// parse second format
System.out.println(DateTime.parse("24/08/2017 07:38:32 +01:00", formatter));
Both dates will be parsed to:
2017-08-24T06:38:32.000Z
Then you can add new formats to the array, as needed.
Java new Date/Time API
Joda-Time is in maintainance mode and is being replaced by the new APIs, so I don't recommend start a new project with it. Even in joda's website it says: "Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).".
If you can't (or don't want to) migrate from Joda-Time to the new API, you can ignore this section.
If you're using Java 8, consider using the new java.time API. It's easier, less bugged and less error-prone than the old APIs.
If you're using Java <= 7, you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. And for Android, there's the ThreeTenABP (more on how to use it here).
The code below works for both.
The only difference is the package names (in Java 8 is java.time and in ThreeTen Backport (or Android's ThreeTenABP) is org.threeten.bp), but the classes and methods names are the same.
The code to parse the inputs is very similar, with minor changes in the format.
And I'm using the Instant class, because you want the output in UTC, and Instant represents a UTC instant:
// format 1
DateTimeFormatter f1 = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss O yyyy", Locale.ENGLISH);
// format 2
DateTimeFormatter f2 = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss XXX");
// formatter with both formats
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
// add format 1
.appendOptional(f1)
// add format 2
.appendOptional(f2)
// create formatter
.toFormatter(Locale.ENGLISH);
// parse first format
System.out.println(Instant.from(formatter.parse("Thu Aug 24 07:38:32 GMT+01:00 2017")));
// parse second format
System.out.println(Instant.from(formatter.parse("24/08/2017 07:38:32 +01:00")));
This will output:
2017-08-24T06:38:32Z
2017-08-24T06:38:32Z
String DOB = new DateTime(Long.parseLong(dob) * 1000, DateTimeZone.UTC ).toString();
// Current
// YYYY-MM-DD
// DOB = "1994-05-10T00:00.000Z"
// Required
// DD-MM-YYYY
// DOB = "10-05-1994"
I want to remove the hh:mm:ss and format the date using Joda-Time DateTimeFormatter.
try this:
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS zzz");
// pass your DOB String
DateTime jodatime = dtf.parseDateTime(DOB);
// Format for output
DateTimeFormatter dtfOut = DateTimeFormat.forPattern("dd-MM-yyyy");
// Print the date
System.out.println(dtfOut.print(jodatime));
tl;dr
Use java.time classes.
Instant.ofEpochSecond( 1_485_748_890L )
.atZone( ZoneId.of( "America/Montreal" ) )
.toLocalDate()
.format(
DateTimeFormatter.ofPattern ( "dd-MM-uuuu" )
.withLocale ( Locale.UK )
)
29-01-2017
Joda-Time
If you want a date-only value without a time-of-day, you should be using the org.joda.time.LocalDate class.
FYI, the Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes. Much of java.time is back-ported to Java 6, Java 7, and Android (see below).
java.time
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate birthdate = LocalDate.of( 1994 , 5 , 10 );
If your input is a count of whole seconds since the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00Z), convert to an Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochSecond( 1_485_748_890L );
To view this moment through the lens of a particular region’s wall-clock time, assign a time zone (ZoneId) to get a ZonedDateTime.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate ld = zdt.toLocalDate();
To generate a String representing the value of your object, call toString for a string in standard ISO 8601 format, YYYY-MM-DD.
ld.toString(): 2017-01-29
For other formats, use the DateTimeFormatter class. You can specify a formatting pattern, or let the class automatically localize.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd-MM-uuuu" ).withLocale ( Locale.UK );
String output = ld.format ( f );
instant.toString(): 2017-01-30T04:01:30Z
zdt.toString(): 2017-01-29T23:01:30-05:00[America/Montreal]
ld.toString(): 2017-01-29
output: 29-01-2017
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 and 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 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….
try this :
String textDate ="1994-05-10T00:00.000Z"; //Date to convert
DateTimeFormatter DATE_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ"); //Default format
SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()); //Needed format
DateTime dateTime = new DateTime(DATE_FORMAT.parseDateTime(textDate), DateTimeZone.forID(current.getID()));
Calendar cal=dateTime.toCalendar(Locale.getDefault());
String formatted = SIMPLE_DATE_FORMAT.format(cal.getTime()); //Final Required date
In my app, I receive dates from a webservice in the form yyyy-MM-dd (e.g. 2016-03-05) and I need to format them as [abbreviated month] [date], e.g. Mar 5. Additionally, I have a start and end date and want to show them as a date range, unless both dates are the same.
Currently I'm using DateUtils.formatDateRange(), which should take care of my requirements and provide proper localization, but I'm running into two problems:
When my end date is the day after my start date, formatDateRange()
only shows the formatted start date. For example, if start date is
2016-03-05 and end date is 2016-03-06, the method returns Mar 5 (but it should be Mar 5 - Mar 6). Why does this happen?
When the end date is in the same month, the month is not shown. For example, if start date is 2016-03-05 and end date is
2016-03-12, the method returns Mar 5 - 12. Is there a way to make it show Mar 5 - Mar 12 instead?
Here is my code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startDate, endDate;
try {
startDate = sdf.parse(startDateString);
endDate = sdf.parse(endDateString);
} catch (ParseException ignored) {
return null;
}
int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH;
return DateUtils.formatDateRange(context, startDate.getTime(), endDate.getTime(), flags);
In the first case, the date formatter is taking your end date in the range as exclusive (as opposed to inclusive in the range). If you simply add one millisecond to the end date, you will see the ranges you expect, because now the date range includes the point in time at midnight for the end date.
In the second case, I'm afraid you are up to the current locale rules for date formatting. You pretty much have to accept what Android thinks is the best formatting, or come up with your own rules for each locale that you want to support.
tl;dr
LocalDate.parse( inputStart )
.format( DateTimeFormatter.ofPattern( "MMM d" ).withLocale( Locale.US ) )
+ " - " +
LocalDate.parse( inputStop )
.format( DateTimeFormatter.ofPattern( "MMM d" ).withLocale( Locale.US ) )
Mar 5 - Mar 6
Details
You can do this quite simply with the java.time classes rather than the troublesome old legacy date-time classes ( Date, SimpleDateFormat ) and the external library DateUtils.
Your input date strings use the standard ISO 8601 format. The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
The LocalDate class represents a date-only value without time-of-day and without time zone.
LocalDate start = LocalDate.parse( "2017-01-23" );
LocalDate stop = LocalDate.parse( "2017-02-14" );
To generate a string with just the abbreviated month name and day-of-month, use DateTimeFormatter.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM d" );
Specify a Locale to determine (a) the human language for translation of name of day, name of month, and such, and (b) the cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
f = f.withLocale( Locale.US ) ; // Or Locale.CANADA_FRENCH, Locale.UK, Locale.ITALY, etc.
Ask the LocalDate to generate a string representing its value.
String output = start.format( f ) + " - " + stop.format( f ) ;
Jan 23 - Feb 14
MonthDay
Sounds like you may be interested in the MonthDay class if needing to work with the concept of a month and a day-of-month but without any year.
MonthDay md = MonthDay.of( 1 , 23 ) ;
Or use the Month enum to specify the month argument.
MonthDay start = MonthDay.of( Month.JANUARY , 23 ) ;
MonthDay stop = MonthDay.of( Month.FEBRUARY , 14 ) ;
To generate a string in standard ISO 8601 format, call toString.
String output = start.toString() ;
--01-23
Or use the same DateTimeFormatter seen above.
String output = start.format( f );
Jan 23
The ISO 8601 defines a format indicating a span of time using a slash character. So your same range of month-day values would be:
String output = start.toString() + "/" + stop.toString() ;
--01-23/--02-14
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.
I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0
as a result. But I want Timestamp like,1312828200000 format.
I cannot understand how to convert that.
My code:
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
If you use getTime() of Date object you will get time in millisecond.
No need to use Timestamp to get your result.
String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
The above code will print something like 1312828200000 you need and this is long value.
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
This line:
"Today is " +timeStampDate
calls TimeStamp.toString() method "which Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds."
The TimeStamp you got internally has the value you want. If you want to get it than use:
System.out.println("Today is " + timeStampDate.getTime());
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " + timeStampDate.getTime());
Or if you don't need the Timestamp, you can directly use date.getTime(). It "Returns the Date as a millisecond value.":
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Today is " + date.getTime());
tl;dr
Use modern java.time classes.
LocalDate.parse(
"13-09-2011" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.atStartOfDay(
ZoneId.of( "Africa/Casablanca" ) // Or use `ZoneOffset.UTC` instead of a zone.
)
.toInstant()
.toEpochMilli()
See this code run live at IdeOne.com.
1315872000000
Details
Apparently you want to represent the first moment of a particular date as a count of milliseconds since the epoch reference of first moment of 1970 in UTC.
java.time
The modern approach uses the java.time classes that years ago supplanted the troublesome legacy classes such as Date, Calendar, and SimpleDateFormat.
First parse your input string as a LocalDate, for a date-only value without time-of-day and without time zone.
Tip: Rather then using such custom formats when exchanging date-time values as text, use standard ISO 8601 formats. The java.time classes use them by default when parsing/generating strings.
String input = "13-09-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Determine the first moment of the day on that date. Doing so requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Never assume the day starts at 00:00. In some zones on some dates, the day may start at another time such as 01:00. Let java.time determine first moment.
ZonedDateTime zdt = ld.startOfDay( z ) ; // Determine first moment of the day on this date in this zone. May not be 00:00.
Adjust to UTC from that zone by extracting a Instant.
Instant instant = zdt.toInstant() ;
Get a count of milliseconds since 1970-01-01T00:00Z. Beware of possible data loss, as an Instant carries a finer resolution of nanoseconds. Any microseconds or nanoseconds will be ignored.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
You can go back the other direction, from a count-from-epoch to a Instant.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch) ;
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.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - 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
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Kotlin
val dateString = "17-09-2021"
val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val date = formatter.parse(dateString) as Date
Log.i("i","Today is " + date.time)
You'll get something that resembles 1616668471659
It may can help you
long time= System.currentTimeMillis();//timestamp in milliseconds of current time
String tp = Long.toString(time);//use timestamp as a string