I have the below code
public Long getEpochTime(String dateToGetItsEpoch) throws ParseException
{
TimeZone timeZone = TimeZone.getTimeZone("UTC");
final String REQUEST_DATE_FORMAT = "dd/MM/yyyy h:m";
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(dateToGetItsEpoch);
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
Date d = cal.getTime();
return d.getTime();
}
If I change the locale of my device to whatever, I always get the UTC time as the return value. Which is correct, however I want to know how is this happening ? How does the device know Which timezone is the date I am giving to it so that it calculates accordingly ?
A Date doesn't have a time zone at all. A SimpleDateFormat does as a default for parsing and formatting; a Calendar does too; a Date doesn't.
Given this sequence of operations:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date localDate = format.parse(dateToGetItsEpoch);
Calendar cal = Calendar.getInstance(timeZone);
cal.setTime(localDate);
format.setTimeZone(timeZone);
final String utcTime = format.format(cal.getTime());
... you're initially parsing the string using the default time zone of the device, then you're formatting it in UTC. Note that the Calendar part is irrelevant here - you'd get the same result with:
TimeZone timeZone = TimeZone.getTimeZone("UTC");
DateFormat format = new SimpleDateFormat(REQUEST_DATE_FORMAT);
Date date = format.parse(dateToGetItsEpoch);
format.setTimeZone(timeZone);
final String utcTime = format.format(date);
I would personally recommend using Joda Time where possible for date/time work in Java, mind you. It's a much cleaner API than Calendar/Date.
java.time
The Answer by Jon Skeet is correct. Here is some code updated to use the modern java.time classes that have supplanted the troublesome legacy date-time classes.
Formatting pattern
Define a formatting pattern to match your inputs.
By the way, yours is a poor choice of formats. Instead I recommend using the standard ISO 8601 formats designed for exchanging date-time values as text.
12-hour versus 24-hour clock
Your input data or formatting pattern has a flaw. You used lowercase h which means one or two digits for an hour in the 12-hour clock (rather than 24-hour clock, which is uppercase H or HH). So your input makes no sense unless you add some indicator of AM or PM. I will assume you mistakenly omitted this from your Question's code.
Locale locale = Locale.US ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd/MM/uuuu h:m a" ).withLocale( locale ) ;
LocalDateTime
Parse such strings as LocalDateTime objects, as they lack an indicator of the intended time zone or offset-from-UTC.
String input = "23/01/2020 4:5 PM" ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
ldt.toString(): 2020-01-23T16:05
Moment
The LocalDateTime object we obtained above does not represent a moment, is not a point on the timeline. We have a time of around 4 PM on the 23rd. But we cannot know if this was meant to be 4 PM in Tokyo, Toulouse, or Toledo — all very different moments several hours apart.
To determine a moment, we must know for certain the intended time zone. Then apply that zone as a ZoneId to get a ZonedDateTime. Then we have arrived at a moment.
Locale is not a time zone
locale of my device to whatever
A Locale has nothing to with time zone. A Locale is used for localizing generated text representing a date-time object.
To localize, specify:
FormatStyle to determine how long or abbreviated should the string be.
Locale to determine:
The human language for translation of name of day, name of month, and such.
The cultural norms deciding issues of abbreviation, capitalization, punctuation, separators, and such.
Example:
Locale l = Locale.CANADA_FRENCH ; // Or Locale.US, Locale.JAPAN, etc.
DateTimeFormatter f =
DateTimeFormatter
.ofLocalizedDateTime( FormatStyle.FULL )
.withLocale( l )
;
String output = myZonedDateTime.format( f );
You could have an engineer from Québec who uses the Locale.CANADA_FRENCH for human language and cultural norms, but while visiting in Japan uses Asia/Tokyo time zone for scheduling appointments.
ZonedDateTime
Back to your LocalDateTime object. If you are certain it was meant to represent a moment as seen in the wall-clock time in Tunisia, then apply a time zone of Africa/Tunis.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
You asked:
How does the device know Which timezone is the date I am giving to it so that it calculates accordingly ?
You were using terrible date-time classes that failed to account for the concept of a date-time lacking an indicator of time zone or offset-from-UTC. So technically, your code is a mess, a hack, unavoidable in those days before Joda-Time and its successor, java.time.
I suggest spending no effort on trying to understand that behavior of Date & Calendar. Just move on to using java.time, the industry-leading date-time handling framework.
Related
I am getting the 4 hours difference on time zone from below lines of code on my device:
I am getting the time in such a way like 2018-09-30T13:45:00Z
My start and End Date is as follow: -
"start_date":"2017-09-13T12:15:00Z",
"end_date":"2018-09-30T13:45:00Z",
Calendar c = Calendar.getInstance(Locale.getDefault());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm");
dateFormatter.setTimeZone(c.getTimeZone());
localStartDate = dateFormatter.parse(startTime);
localEndDate = dateFormatter.parse(endTime);
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String monthName = monthFormat.format(localStartDate);
eventDate.setMonth(monthName);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dateName = dateFormat.format(localStartDate);
eventDate.setDate(dateName);
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String dayName1 = dayNameFormat.format(localStartDate);
String dayName2 = dayNameFormat.format(localEndDate);
eventDate.setDayName1(dayName1);
eventDate.setDayName2(dayName2);
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
String startTimeName = timeFormat.format(localStartDate);
String endTimeName = timeFormat.format(localEndDate);
System.out.println("My Start date and end date==>>>"+startTimeName+" " +endTimeName );
Problem: Getting the 4 hours difference from above code, as I am setting my time zone to BOSTON(US), getting error.
My result from the below #Hugo solution is as below
And i am expecting the result as below
Please check it once..I have also set the TimeZone of Eastern DayLight Time but not getting proper solution..please check it once..And let me know
SimpleDateFormat and Calendar uses the JVM default timezone (unless you set a different one on them), and the default timezone can be different in each device/machine/environment. Not only that, this default can be changed without notice, even at runtime, so it's better to always make it explicit which one you're using.
When you do things like:
Calendar c = Calendar.getInstance(Locale.getDefault());
dateFormatter.setTimeZone(c.getTimeZone());
monthFormat.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getDisplayName()));
The Calendar is created with the default timezone, so dateFormatter will also have the same zone. So does monthFormat, and also the other formatters you created. The only formatter set to a different zone is the first one (which is set to UTC).
Also, the second formatter is redundant (it does the same thing that the first one is already doing: parsing the String to a Date), so you can remove it.
Assuming that your input is a String with the value 2018-09-30T13:45:00Z: the Z in the end indicates that this date is in UTC. So you should parse it using a formatter set to UTC. So, instead of using c.getTimeZone() and TimeZone.getDefault(), you should use only TimeZone.getTimeZone("UTC").
For the output, you must set the formatters with the timezone you want to convert to. If the timezone is "EDT", set to it (but don't use exactly "EDT", see below). If you want to use the JVM default, use TimeZone.getDefault() - just check this value before, to make sure the default is what you need.
Just keep in mind that short names like "EDT" and "EST" are not real timezones. Those abbreviations are ambiguous and not standard. Prefer to use IANA timezones names (always in the format Region/City, like America/New_York or Europe/Berlin).
So, when you do TimeZone.getTimeZone("EDT"), it usually returns "GMT" (because "EDT" is not recognized, and "GMT" is returned as default). That's because "EDT" is used by more than one timezone, so you must choose specifically which one you're using (I'm using America/New_York in these examples).
Another detail is that in the first 2 formatters you use hh, which means "hour of am/pm" (values from 1 to 12), but the input doesn't have AM/PM designators to properly resolve this. You need to change it to HH ("hour of day", with values from 0 to 23).
// input is in UTC
TimeZone inputZone = TimeZone.getTimeZone("UTC");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
formatter.setTimeZone(inputZone);
Date localStartDate = formatter.parse(startTime);
Date localEndDate = formatter.parse(endTime);
...
// removed the second formatter (it was redundant)
// output is in EST (America/New_York)
// or use TimeZone.getDefault() to get JVM default timezone
TimeZone outputZone = TimeZone.getTimeZone("America/New_York");
SimpleDateFormat monthFormat = new SimpleDateFormat("MMM");
monthFormat.setTimeZone(outputZone);
...
SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
dateFormat.setTimeZone(outputZone);
...
SimpleDateFormat dayNameFormat = new SimpleDateFormat("EEEE");
dayNameFormat.setTimeZone(outputZone);
...
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm a");
timeFormat.setTimeZone(outputZone);
...
System.out.println("My Start date and end date==>>>" + startTimeName + " " + endTimeName);
With this, you're explicity using UTC for input and a specific timezone for output, instead of relying on the JVM default timezone (which can be different in each device and you can't control).
The output is:
My Start date and end date==>>>08:15 AM 09:45 AM
Java new Date/Time API
The old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
First you can use a org.threeten.bp.Instant to parse the input, because it's in UTC (designated by the Z in the end). Then you use a org.threeten.bp.ZoneId to convert it to a org.threeten.bp.ZonedDateTime:
// output timezone
// or use ZoneId.systemDefault() to get JVM default timezone
ZoneId zone = ZoneId.of("America/New_York");
// parse the inputs
ZonedDateTime startDate = Instant.parse(startTime).atZone(zone);
ZonedDateTime endDate = Instant.parse(endTime).atZone(zone);
Then you can use these objects to get the other fields:
// get month name
System.out.println(startDate.getMonth().getDisplayName(TextStyle.SHORT, Locale.getDefault()));
This is equivalent to MMM pattern, and it will print the month name in the default locale. If you want the month name in a specific language, just use another java.util.Locale value (such as Locale.ENGLISH or any other one as described in the javadoc).
The org.threeten.bp.format.TextStyle defines if the month name will be narrow (usually just one letter), short (usually 2 or 3 letters) or full (the full name). The output varies according to the locale used.
I personally prefer to not use the default locale, because it can be changed without notice, even at runtime. It's always better to specify the locale you want.
To get the day of month, you can choose to get it as an int or as a formatted String (using a org.threeten.bp.format.DateTimeFormatter):
// get day of month as int
int day = startDate.getDayOfMonth(); // 30
// get day of month as formatted string
String dayStr = DateTimeFormatter.ofPattern("dd").format(startDate); // 30
To get the day of week, it's similar to the code used to get the month:
// get day of week
System.out.println(startDate.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.getDefault()));
The same logic applies here: the TextStyle defines how the name will be (in this case, FULL is equivalen to EEEE, and it prints the full name), and the locale defines the language used.
Finally, to get the corresponding time, you can use another DateTimeFormatter:
// get time
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("hh:mm a");
System.out.println(fmt.format(startDate)); // 08:15 AM
System.out.println(fmt.format(endDate)); // 09:45 AM
This will the date/time in the timezone you chose for the output.
If you're going to use the JVM default (ZoneId.systemDefault()), just check its value before to make sure it's the one you want (it might not be because this can be changed at runtime, so it's always better to specify one).
Example, from 1 min ago
i use api and time response result from Api service as:
{
"date_time":"2016-03-10 03:20:30"
}
Please discuss step by step, And if available how can programticly display it in Arabic format
منذ 15 دقيقة
My Code for date in list view adapter
TextView date_time = (TextView) convertView.findViewById(R.id.date_time_list_home);
date_time.setText(m.dateTime());
First, for any date/time manipulation on Android, I highly recommend using the ThreeTenABP library. This is a back port of the Java 8 java.time.* package, circumventing the notoriously disappointing java.util.Date and java.util.Calendar classes.
To parse your "date_time" using this library, you can use the following code:
// I set the ZoneId to systemDefault, but you should really use the ZoneId of the server
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
.withZone(ZoneId.systemDefault());
Instant instant = formatter.parse(m.dateTime(), Instant.FROM);
Android provides the DateUtils class to display date and time information. This class takes into account system settings such as Locale and 12/24-hour format. Therefore, if the Locale of the device is set to any of the Arabic locales (ar_), the date/time will be displayed in a format suited for it.
String display = DateUtils.getRelativeTimeSpanString(
instant.toEpochMilli(),
Instant.now().toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
The last parameter in getRelativeTimeSpanString is the minimum resolution, so setting DateUtils.MINUTE_IN_MILLIS will not display the difference in seconds.
If you insist on using the Java 7 classes, here is the same code using them:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = format.parse(m.dateTime());
String display = DateUtils.getRelativeTimeSpanString(
date.getTime(),
new Date(),
DateUtils.MINUTE_IN_MILLIS);
date_time.setText(display);
If you need a "transition resolution" greater than a single day (i.e. you want to display a date/time that is further than one day in the past as "… days ago") you can use the DateUtils.getRelativeDateTimeString() method instead:
String display = DateUtils.getRelativeDateTimeString(
mContext,
instant.toEpochMilli(),
DateUtils.MINUTE_IN_MILLIS,
DateUtils.WEEK_IN_MILLIS,
DateUtils.FORMAT_ABBREV_ALL);
Any date that is further back than the transitionResolution (in this case, one week) will be displayed in an appropriate date format, instead of the relative format. The minResolution and transitionResolution can be any long value, DateUtils contains other convenient constants such as MONTH_IN_MILLIS and YEAR_IN_MILLIS.
The last parameter takes an integer for formatting flags. These flags override the default formatting that DateUtils uses for each Locale; view the documentation for more information.
I am using SimpleDateFormat to format my date "dd Mmm yyy" format but I want Mmm to be translated to Malay. I am using below code to do so but unable to get the expected result.
SimpleDateFormat sdf = new SimpleDateFormat(format,new Locale("ms","MY"));
return sdf.format(date);
You Should Try This Way to format locale date:
DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
String formattedDate = f.format(new Date());
System.out.println("Date: " + formattedDate);
I Hope this will work. Reference link: Localized date format in Java
I had not set new Locale constructor properly to handle Malay language support.
String format = "MMM dd yyyy"
SimpleDateFormat sdf = new SimpleDateFormat(format, new Locale("ms","MY","MY"));
return sdf.format(date);
java.time
You are using old date-time classes that have proven to be poorly designed, confusing, and troublesome. They have been supplanted by the java.time classes built into Java 8 and later. Defined by JSR 310. Much of that functionality has been back-ported to Java 6 & 7 in the ThreeTen-Backport project and further adapted to Android in the ThreeTenABP project.
If you have a java.util.Date object, convert it to an Instant object, a moment on the timeline in UTC with a resolution of nanoseconds. New methods have been added to the old classes to facilitate conversion.
Instant instant = myJavaUtilDate.toInstant();
Or get the current moment. In Java 8, the current moment is captured only with millisecond resolution, despite the Instant class’ capacity for nanoseconds. In Java 9, the current moment is captured with up to nanosecond resolution (depending on your computer hardware clock capability).
Instant instant = Instant.now();
Apply a time zone for the locality whose wall-clock time you want to see. This is important even for a date-only value as the date varies around the world at any given moment. A new day dawns earlier in the east.
I choose a New Zealand time zone arbitrarily, for demonstration. Apply a ZoneId to get a ZonedDateTime object.
Use proper time zone names, never the 3-4 letter codes you see in the media such as IST or EST. Such codes are not standardized nor even unique.
ZoneId zoneId = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
The time zone has nothing to do with localization into a human language such as Malay. A Locale handles that, as well as defining cultural norms to use for issues such as ordering of the elements or using period vs comma.
My example assumes you were correct in specifying the language and country/culture codes.
Locale locale = new Locale( "ms" , "MY" );
The java.time.format package has classes that can automatically localize when generating a String to represent a java.time value.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM );
When defining a formatter, remember to specify the Locale. If omitted, your JVM’s current default Locale will be applied implicitly. That default can change at any moment, even during runtime! So better to be always be explicit.
formatter = formatter.withLocale( locale );
String output = zdt.format( formatter );
23 Mei 2016
By comparison when using Locale.US:
May 23, 2016
And when using Locale.CANADA_FRENCH:
2016-05-23
I am not sure if below code works for you, its written in Scala its almost same in Java.
val malaysia = new Locale("ms","MY","MY")
val cal = Calendar.getInstance(malaysia)
val df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, malaysia)
println(df.format(cal.getTime()))
results from above code is
Isnin 23 Mei 2016 9:55:44 AM IST
You need to do this way;
Edit 1:
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, new Locale("ms","MY"));
String formattedDate = dateFormat.format(new Date());
Hope this would help you.
This code solved my problem and get the result in Bengali.
val local = Locale("bn")
val dateFormat = DateFormat.getDateInstance(DateFormat.FULL, local)
val stringDate = dateFormat.format(date)
Log.e("", stringDate)
And the output is:
মঙ্গলবার, ২৩ ফেব্রুয়ারী, ২০২১
if you want your date to be formatted to device locale then use the below code
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate = format.parse(strDate2);
long milliDate = newDate.getTime()+getCurrentTimezoneOffset();
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(milliDate);
return format.format(cal.getTime());
Every time I try to get the current time (I have a button for that, lets call it "botonGuardarEstado") I get the same hours and minutes. What I have noted is that the time I got is the time when I opened the app. What I mean is, if I opened the app at 7:10 a.m. and press the button at 7:12 a.m., I get 7:10 a.m. Here is my code:
DateFormat formatoFecha = new SimpleDateFormat("HH:mm dd/MM/yyyy");
String fecha = formatoFecha.format(Calendar.getInstance().getTime());
I am not getting weird values like different years or anything like that, and the format works well, the problem is that i get the same hours:minutes everytime i push the button. I alredy tried different ways of getting the date and time, things like Date(), or even getting only the hours and minutes using something like this
Calendar cal = Calendar.getInstance();
int mins = cal.get(Calendar.MINUTE);
but still got the same values.
I have the following class
private class InfoArchivo {
String temperatura, humedad, gas, humo, iluminacion, riego, ventilacion, fecha;
public InfoArchivo(String temperatura, String humedad, String gas, String humo, String iluminacion, String riego, String ventilacion, String fecha){
this.temperatura = temperatura;
this.humedad = humedad;
this.gas = gas;
this.humo = humo;
this.iluminacion = iluminacion;
this.riego = riego;
this.fecha = fecha;
if(!ventilacion.equals("0"))
this.ventilacion = "1";
else
this.ventilacion = "0";
}
I have an array of instances of that class. What i am trying to do is write a csv file using the array. Every other data (temperatura, humedad, etc) is correct. The only thing causing trouble is the date (fecha). The creation of the csv file is done until i press another button. When i press the botonGuardarEstado button i get the date, make an instance of the class InfoArchivo and add it to the array
EDIT: Also tried with this but still have the same issue:
Instant instant = Instant.now();
ZoneId zoneId = ZoneId.of("America/Guatemala");
ZonedDateTime zdt = ZonedDateTime.ofInstant(instant, zoneId);
DateTimeFormatter formato = DateTimeFormatter.ofPattern("HH:mm dd/MM/yyyy");
String fecha = zdt.format(formato);
Not a date-time problem
Your code as shown is correct.
So your problem must be happening elsewhere in your app. Perhaps you are not correctly feeding the new String (fecha) to the user interface. Or perhaps you need to do something to refresh the display of that new String’s value. We cannot help you further as you did not provide that other code.
java.time
By the way, you are using outmoded classes. The old date-time classes that have proven to be so confusing and troublesome have been supplanted by the java.time framework. See the Oracle Tutorial.
Java 8 and later: The java.time framework is built-in.
Java 7 & 6: Use the backport of java.time.
Android: Use this wrapped version of that backport.
Instant
An Instant is a moment on the timeline in UTC with resolution up to nanoseconds.
Instant instant = Instant.now(); // Current moment in UTC.
Time Zone
Apply a time zone (ZoneId) to get a ZonedDateTime. If you omit the time zone your JVM’s current default time zone is implicitly applied. Better to specify explicitly the desired/expected time zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Or "Asia/Kolkata", "Europe/Paris", and so on.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
Generating Strings
You can easily generate a String as a textual representation of the date-time value. You can go with a standard format, your own custom format, or an automatically localized format.
ISO 8601
You can call the toString methods to get text formatted using the common and sensible ISO 8601 standard.
String output = instant.toString();
2016-03-19T05:54:01.613Z
Custom format
Or specify your own particular formatting pattern with the DateTimeFormatter class.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM/yyyy hh:mm a" );
Specify a Locale for a human language (English, French, etc.) to use in translating the name of day/month and also in defining cultural norms such as the order of year and month and date. Note that Locale has nothing to do with time zone.
formatter = formatter.withLocale( Locale.US ); // Or Locale.CANADA_FRENCH or such.
String output = zdt.format( formatter );
Localizing
Better yet, let java.time do the work of localizing automatically.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.MEDIUM );
String output = zdt.format( formatter.withLocale( Locale.US ) ); // Or Locale.CANADA_FRENCH and so on.
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