This question already has answers here:
Convert String to java.util.Date
(4 answers)
Display current time in 12 hour format with AM/PM
(15 answers)
Java - parse date with AM/PM next to seconds (no space)
(5 answers)
Closed 3 years ago.
This is my sample code
String dt = "Oct 24 2019 12:00:00.000 AM UTC";
String dt1="Oct 24 2019 11:59:59.000 PM UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy HH:mm:ss.SSS
aa zzz");
Date date = df.parse(dt);
Date date1 = df.parse(dt1);
long epoch = date.getTime();
long epoch1 = date1.getTime();
System.out.println(epoch);
System.out.println(epoch1);
Here specifying the AM and PM but its not taking the value for that and throwing the exception as
{"error_code":"INVALID_PARAMETER_VALUE","message":"Time range must have a start time earlier than the end time"}
How to specify AM/PM in the java code.
How can I take yesterday's date and time for today in java code as an input to convert to epoch.
tl;dr
ZonedDateTime
.parse(
"Oct 24 2019 12:00:00.000 AM UTC" ,
DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US )
)
.toInstant()
.toEpochMilli()
1571875200000
java.time
Two problems:
As commented by Heuberger, you are using incorrect formatting codes.
You are using terrible date-time classes supplanted years ago by the modern java.time classes.
Your inputs, renamed for clarity.
String inputStart = "Oct 24 2019 12:00:00.000 AM UTC";
String inputStop = "Oct 24 2019 11:59:59.000 PM UTC";
Define a formatting pattern to match your inputs.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM d uuuu hh:mm:ss.SSS a z" ).withLocale( Locale.US );
Parse inputs.
ZonedDateTime zdtStart = ZonedDateTime.parse( inputStart , f );
ZonedDateTime zdtStop = ZonedDateTime.parse( inputStop , f );
Calculate elapsed time. We should get one second less than 24 hours.
Duration d = Duration.between( zdtStart , zdtStop );
Apparently you want the count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z. First extract the building-block class, Instant, from each ZonedDateTime. An Instant represents a moment in UTC. This class lets you interrogate for the count since epoch. Note that java.time classes resolve to nanoseconds. So asking for milliseconds can result in data loss, ignoring any microseconds or nanoseconds.
Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;
long millisStart = start.toEpochMilli() ;
long milliStop = stop.toEpochMilli() ;
Dump to console.
System.out.println( "zdtStart = " + zdtStart );
System.out.println( "zdtStop = " + zdtStop );
System.out.println( "d = " + d );
System.out.println( "start = " + start );
System.out.println( "stop = " + stop );
System.out.println( "millisStart = " + millisStart );
System.out.println( "milliStop = " + milliStop );
zdtStart = 2019-10-24T00:00Z[UTC]
zdtStop = 2019-10-24T23:59:59Z[UTC]
d = PT23H59M59S
start = 2019-10-24T00:00:00Z
stop = 2019-10-24T23:59:59Z
millisStart = 1571875200000
milliStop = 1571961599000
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.
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….
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.
You need to use the following date format:
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);
For AM/PM Marker, 'a' is used. For reference
e.g.
import java.util.*;
import java.text.*;
public class Main
{
public static void main(String[] args) {
try{
String dt = "Oct 24 2019 12:00:00.000 AM UTC";
String dt1="Oct 24 2019 11:59:59.000 PM UTC";
SimpleDateFormat df = new SimpleDateFormat("MMM dd yyyy hh:mm:ss.SSS a zzz",Locale.US);
Date date = df.parse(dt);
Date date1 = df.parse(dt1);
long epoch = date.getTime();
long epoch1 = date1.getTime();
System.out.println(epoch);
System.out.println(epoch1);
}catch(Exception e){
e.printStackTrace();
}
}
}
output:
1571918400000
1571918399000
Related
I am working on android project and i receive from API the time in format like this "10:12:57 am" (12 hour format) and I want to display it in format "10:12" just like this (on a 24 hour clock). How to reformat that time?
So 12:42:41 am should become 00:42. And 02:13:39 pm should be presented as 14:13.
Using java.time (Modern Approach)
String str = "10:12:57 pm";
DateTimeFormatter formatter_from = DateTimeFormatter.ofPattern( "hh:mm:ss a", Locale.US ); //Use pattern symbol "hh" for 12 hour clock
LocalTime localTime = LocalTime.parse(str.toUpperCase(), formatter_from );
DateTimeFormatter formatter_to = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ); // "HH" stands for 24 hour clock
System.out.println(localTime.format(formatter_to));
See BasilBourque answer below and OleV.V. answer here for better explanation.
Using SimpleDateFormat
String str = "10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss a", Locale.US);
//Locale is optional. You might want to add it to avoid any cultural differences.
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm", Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
If your input is 10:12:57 am, output will be 10:12. And if string is 10:12:57 pm, output will be 22:12.
tl;dr
LocalTime // Represent a time-of-day, without a date and without a time zone.
.parse( // Parse an input string to be a `LocalTime` object.
"10:12:57 am".toUpperCase() , // The cultural norm in the United States expects the am/pm to be in all-uppercase. So we convert our input value to uppercase.
DateTimeFormatter.ofPattern( "hh:mm:ss a" , Locale.US ) // Specify a formatting pattern to match the input.
) // Returns a `LocalTime` object.
.format( // Generate text representing the value in this date-time object.
DateTimeFormatter.ofPattern( "HH:mm" , Locale.US ) // Note that `HH` in uppercase means 24-hour clock, not 12-hour.
) // Returns a `String`.
10:12
java.time
The modern approach uses the java.time classes that years ago supplanted the terrible Date & Calendar & SimpleDateFormat classes.
The LocalTime class represents a time-of-day in a generic 24-hour day, without a date and without a time zone.
Parse your string input as a LocalTime object.
String input = ( "10:12:57 am" );
DateTimeFormatter fInput = DateTimeFormatter.ofPattern( "HH:mm:ss a" , Locale.US );
LocalTime lt = LocalTime.parse( input.toUpperCase() , fInput ); // At least in the US locale, the am/pm is expected to be in all uppercase: AM/PM. So we call `toUppercase` to convert input accordingly.
lt.toString(): 10:12:57
Generate a String with text in the hour-minute format you desire. Note that HH in uppercase means 24-hour clock.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "HH:mm" , Locale.US );
String output = lt.format( fOutput );
output: 10:12
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….
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.
Try this:
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
try {
Date date = parseFormat.parse("10:12:57 pm");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
catch (Exception e) {
e.printStackTrace();
}
The gives:
10:12:57 pm = 22:12
You can use such formatters:
SimpleDateFormat formatterFrom = new SimpleDateFormat("hh:mm:ss aa");
SimpleDateFormat formatterTo = new SimpleDateFormat("HH:mm");
Date date = formatterFrom.parse("10:12:57 pm");
System.out.println(formatterTo.format(date));
String str ="10:12:57 pm";
SimpleDateFormat formatter_from = new SimpleDateFormat("hh:mm:ss aa", Locale.US);
SimpleDateFormat formatter_to = new SimpleDateFormat("HH:mm",Locale.US);
try {
Date d = formatter_from.parse(str);
System.out.println(formatter_to.format(d));
} catch (ParseException e) {
e.printStackTrace();
}
I am pragmatically building a nested JSON from a table. Json looks something like this:
{"date":"03-16-2018 06:57:02",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 20:41:57",
},
{
"motorstate":0,
"startTime":"03-16-2018 06:57:02",
}
]
},
{"date":"03-15-2018 08:08:48",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 03:53:30",
}
]
}
If you look into the above example, the second record:
{"date":"03-15-2018 08:08:48",
"details":
[
{
"motorstate":0,
"startTime":"03-16-2018 03:53:30",
}
]
}
The dates are mismatching. This is because the date shown here is in IST but actually stored in UTC in my Google Datastore. In UTC, its still 03-15-2018 and not 03-16-2018.
My question is how can we perform a date difference in different timezones other than UTC in Java? The Date.getTime() method always give the difference in UTC and not in local Timezone.
tl;dr
Date difference in different timezones in java
Period.between(
LocalDateTime.parse(
"03-15-2018 08:08:48" ,
DateTimeFormatter.ofPattern( “MM-dd-uuuu HH:mm:ss” )
)
.atZone( ZoneId.of( ”Asia/Kolkata" ) )
.toLocalDate()
,
LocalDate.now( ZoneId.of( ”Asia/Kolkata" ) )
)
Details
The modern approach uses the java.time classes rather than the troublesome old me old legacy date-time classes such as Date and Calendar.
Tip: Avoid custom formatting patterns when serializing date-time values to text. Use standard ISO 8601 formats only.
Tip: when exchanging date-time values as text, always include an indicator of the offset-from-UTC and the time zone name.
First, parse your input strings as LocalDateTime because they lack any indication of offset or zone.
Define a formatting pattern to match input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( “MM-dd-uuuu HH:mm:ss” ) ;
Parse.
String input = "03-15-2018 08:08:48" ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
You claim to know that these inputs were intended to represent a moment in India time. Apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( ”Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
To get the date-only value, extract a LocalDate.
LocalDate ld = zdt.toLocalDate() ;
To represent the delta between dates as a number of years, months, and days unattached to the timeline, use Period.
Period p = Period.between( ldt , LocalDate.now( z ) ) ;
For a count of total days.
long days = ChronoUnit.DAYS.between( start , stop ) ;
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, 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
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….
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.
public String getSummary(String deviceGuid)
{
Query<com.google.cloud.datastore.Entity> query
= Query.newEntityQueryBuilder()
.setKind("sensordata")
.setFilter(PropertyFilter.eq("deviceguid", deviceGuid))
.setOrderBy(OrderBy.desc("startTime"))
.build();
QueryResults<com.google.cloud.datastore.Entity> resultList =
datastore.run(query);
if(!resultList.hasNext())
{
log.warning("No record found..");
return "No record found";
}
com.google.cloud.datastore.Entity e =null;
com.google.cloud.datastore.Entity pe =null;
SensorDataOut sensorDataOut = new SensorDataOut();
SensorSummaryDataOut summary = new SensorSummaryDataOut();
TotalSummaryDataOut totalSummary = new TotalSummaryDataOut();
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("IST"));
Calendar calendar1 = Calendar.getInstance();
calendar1.setTimeZone(TimeZone.getTimeZone("IST"));
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
SimpleDateFormat sdf1 = new SimpleDateFormat("MM-dd-yyyy");
//sdf.setTimeZone(TimeZone.getTimeZone("IST"));
long stopTime;
long startTime;
long pStartTime;
long diffTime;
long diffDay;
Date pDateWithoutTime;
Date eDateWithoutTime;
while(resultList.hasNext())
{
e = resultList.next();
startTime = (e.contains("startTime"))?e.getTimestamp("startTime").toSqlTimestamp().getTime():0;
stopTime = (e.contains("stopTime"))?e.getTimestamp("stopTime").toSqlTimestamp().getTime():0;
//log.info("Start Date : " + e.getTimestamp("startTime").toString() + " - " + String.valueOf(startTime));
//log.info("Stop Date : " + e.getTimestamp("stopTime").toString() + " - " + String.valueOf(stopTime));
//log.info("Usage Volume :" + String.valueOf(e.getLong("usageVolume")));
sensorDataOut = new SensorDataOut();
calendar.setTimeInMillis(stopTime);
sensorDataOut.stopTime = sdf.format(calendar.getTime());
calendar.setTimeInMillis(startTime);
sensorDataOut.startTime = sdf.format(calendar.getTime());
sensorDataOut.motorstate = (e.contains("motorstate"))?(int)e.getLong("motorstate"):-1;
sensorDataOut.startVolume = (e.contains("startVolume"))?(int)e.getLong("startVolume"):-1;
sensorDataOut.stopVolume = (e.contains("stopVolume"))?(int)e.getLong("stopVolume"):-1;
sensorDataOut.usageTime = (e.contains("usageTime"))?e.getLong("usageTime"):-1;
sensorDataOut.usageVolume = (e.contains("usageVolume"))?(int)e.getLong("usageVolume"):-1;
if(pe!=null)
{
//Get the date difference in terms of days. If it is same day then add the volume consumed
pStartTime= pe.getTimestamp("startTime").toSqlTimestamp().getTime();
try{
calendar.setTimeInMillis(pStartTime);
pDateWithoutTime = sdf1.parse(sdf1.format(calendar.getTime()));
calendar1.setTimeInMillis(e.getTimestamp("startTime").toSqlTimestamp().getTime());
eDateWithoutTime = sdf1.parse(sdf1.format(calendar1.getTime()));
}
catch(Exception ex){
log.info("Exception while parsing date");
continue;
}
diffTime = Math.abs(pDateWithoutTime.getTime() - eDateWithoutTime.getTime());
diffDay = TimeUnit.DAYS.convert(diffTime, TimeUnit.MILLISECONDS);
//log.info("pDateWithoutTime: " + pDateWithoutTime + ", eDateWithoutTime: " + eDateWithoutTime + ", consumedVolume: "
// + sensorDataOut.usageVolume;
if(diffDay!=0) //If not same day
{
totalSummary.totVolume = totalSummary.totVolume + summary.totVolume;
totalSummary.totDuration = totalSummary.totDuration + summary.totDuration;
totalSummary.details.add(summary);
summary = new SensorSummaryDataOut();
}
}
summary.date = sensorDataOut.startTime;
summary.totVolume = summary.totVolume + sensorDataOut.usageVolume;
summary.totDuration = summary.totDuration + sensorDataOut.usageTime;
summary.details.add(sensorDataOut);
pe = e;
}
if(summary.details.size()>0)
{
totalSummary.totVolume = totalSummary.totVolume + summary.totVolume;
totalSummary.totDuration = totalSummary.totDuration + summary.totDuration;
totalSummary.details.add(summary);
summary = new SensorSummaryDataOut();
}
totalSummary.avgVolume = totalSummary.totVolume/totalSummary.details.size();
totalSummary.deviceguid = deviceGuid;
String json = "";
Gson gson = new Gson();
json = gson.toJson(totalSummary);
return json;
} //End of Function
Below method will return you your UTC time to current Timezone and this worked for me
public static Date getLocalDateObjFromUTC(String date, String time) throws ParseException {
String dateAndTimeInUTC = date + " " + time;
SimpleDateFormat localDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
localDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date dateInLocalTimeZone = localDateFormat.parse(dateAndTimeInUTC);
return dateInLocalTimeZone;
}
I have a SimleDateFormat like this
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
String date = format.format(Date.parse(payback.creationDate.date));
I'm giving date with the format like "Jan,23,2014".
Now, I want to get day, month and year separately. How can I implement this?
If you need to get the values separately, then use more than one SimpleDateFormat.
SimpleDateFormat dayFormat = new SimpleDateFormat("dd");
String day = dayFormat.format(Date.parse(payback.creationDate.date));
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
String month = monthFormat .format(Date.parse(payback.creationDate.date));
etc.
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm", Locale.ENGLISH);
Date theDate = format.parse("JAN 13,2014 09:15");
Calendar myCal = new GregorianCalendar();
myCal.setTime(theDate);
System.out.println("Day: " + myCal.get(Calendar.DAY_OF_MONTH));
System.out.println("Month: " + myCal.get(Calendar.MONTH) + 1);
System.out.println("Year: " + myCal.get(Calendar.YEAR));
Wow, SimpleDateFormat for getting string parts? It can be solved much easier if your input string is like "Jan,23,2014":
String input = "Jan,23,2014";
String[] out = input.split(",");
System.out.println("Year = " + out[2]);
System.out.println("Month = " + out[0]);
System.out.println("Day = " + out[1]);
Output:
Year = 2014
Month = Jan
Day = 23
But if you really want to use SimpleDateFormat because of some reason, the solution will be the following:
String input = "Jan,23,2014";
SimpleDateFormat format = new SimpleDateFormat("MMM,dd,yyyy");
Date date = format.parse(input);
Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
calendar.setTime(date);
System.out.println(calendar.get(Calendar.YEAR));
System.out.println(calendar.get(Calendar.DAY_OF_MONTH));
System.out.println(new SimpleDateFormat("MMM").format(calendar.getTime()));
Output:
2014
23
Jan
The accepted answer here suggests to use more than one SimpleDateFormat, but it's possible to do this using one SimpleDateFormat instance and calling applyPattern.
Note: I believe this post would also be helpful for those who were searching for setPattern() just like me.
Date date=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
simpleDateFormat.applyPattern("dd");
System.out.println("Day : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("MMM");
System.out.println("Month : " + simpleDateFormat.format(date));
simpleDateFormat.applyPattern("yyyy");
System.out.println("Year : " + simpleDateFormat.format(date));
tl;dr
Use LocalDate class.
LocalDate
.parse(
"Jan,23,2014" ,
DateTimeFormatter.ofPattern( "MMM,dd,uuuu" , Locale.US )
)
.getYear()
… or .getMonthValue() or .getDayOfMonth.
java.time
The other Answers use outmoded classes. The java.time classes supplant those troublesome old legacy classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
String input = "Jan,23,2014";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMM,d,uuuu" );
LocalDate ld = LocalDate.parse( input , f );
Interrogate for the parts you want.
int year = ld.getYear();
int month = ld.getMonthValue();
int dayOfMonth = ld.getDayOfMonth();
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….
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.
Use this to parse "Jan,23,2014"
SimpleDateFormat fmt = new SimpleDateFormat("MMM','dd','yyyy");
Date dt = fmt.parse("Jan,23,2014");
then you can get whatever part of the date.
Are you accepting this ?
int day = 25 ; //25
int month =12; //12
int year = 1988; // 1988
Calendar c = Calendar.getInstance();
c.set(year, month-1, day, 0, 0);
SimpleDateFormat format = new SimpleDateFormat("MMM dd,yyyy hh:mm");
System.out.println(format.format(c.getTime()));
Display as Dec 25,1988 12:00
UPDATE : based on Comment
DateFormat format = new SimpleDateFormat("MMM");
System.out.println(format.format(format.parse("Jan,23,2014")));
NOTE: Date.parse() is #deprecated and as per API it is recommend to use DateFormat.parse
public static String getDate(long milliSeconds, String dateFormat) {
// Create a DateFormatter object for displaying date in specified
// format.
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat,
Locale.getDefault());
// Create a calendar object that will convert the date and time value in
// milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);
return formatter.format(calendar.getTime());
}
I want to know what the current day of the week is (Monday, Tuesday...) in the user's local language. For example, "Lundi" "Mardi" etc... if the user is French.
I have read this post, it but it only returns an int, not a string with the day in the user's language: What is the easiest way to get the current day of the week in Android?
More generally, how do you get all the days of the week and all the months of the year written in the user's language ?
I think that this is possible, as for example the Google agenda gives the days and months written in the user's local language.
Use SimpleDateFormat to format dates and times into a human-readable string, with respect to the users locale.
Small example to get the current day of the week (e.g. "Monday"):
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Try this:
int dayOfWeek = date.get(Calendar.DAY_OF_WEEK);
String weekday = new DateFormatSymbols().getShortWeekdays()[dayOfWeek];
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
To make things shorter You can use this:
android.text.format.DateFormat.format("EEEE", date);
which will return day of the week as a String.
Hers's what I used to get the day names (0-6 means monday - sunday):
public static String getFullDayName(int day) {
Calendar c = Calendar.getInstance();
// date doesn't matter - it has to be a Monday
// I new that first August 2011 is one ;-)
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%tA", c);
}
public static String getShortDayName(int day) {
Calendar c = Calendar.getInstance();
c.set(2011, 7, 1, 0, 0, 0);
c.add(Calendar.DAY_OF_MONTH, day);
return String.format("%ta", c);
}
Try this...
//global declaration
private TextView timeUpdate;
Calendar calendar;
.......
timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()
.......
//in onStart()
calendar = Calendar.getInstance();
//date format is: "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());
//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");
The result is...
tl;dr
String output =
LocalDate.now( ZoneId.of( "America/Montreal" ) )
.getDayOfWeek()
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
java.time
The java.time classes built into Java 8 and later and back-ported to Java 6 & 7 and to Android include the handy DayOfWeek enum.
The days are numbered according to the standard ISO 8601 definition, 1-7 for Monday-Sunday.
DayOfWeek dow = DayOfWeek.of( 1 );
This enum includes the getDisplayName method to generate a String of the localized translated name of the day.
The Locale object specifies a human language to be used in translation, and specifies cultural norms to decide issues such as capitalization and punctuation.
String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
To get today’s date, use the LocalDate class. Note that a time zone is crucial as for any given moment the date varies around the globe.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
DayOfWeek dow = today.getDayOfWeek();
String output = dow.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ;
Keep in mind that the locale has nothing to do with the time zone.two separate distinct orthogonal issues. You might want a French presentation of a date-time zoned in India (Asia/Kolkata).
Joda-Time
UPDATE: The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
The Joda-Time library provides Locale-driven localization of date-time values.
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( zone );
Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter formatterUnJourQuébécois = DateTimeFormat.forPattern( "EEEE" ).withLocale( locale );
String output = formatterUnJourQuébécois.print( now );
System.out.println("output: " + output );
output: samedi
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….
Sorry for late reply.But this would work properly.
daytext=(textview)findviewById(R.id.day);
Calender c=Calender.getInstance();
SimpleDateFormat sd=new SimpleDateFormat("EEEE");
String dayofweek=sd.format(c.getTime());
daytext.setText(dayofweek);
I just use this solution in Kotlin:
var date : String = DateFormat.format("EEEE dd-MMM-yyyy HH:mm a" , Date()) as String
If you are using ThreetenABP date library bt Jake Warthon you can do:
dayOfWeek.getDisplayName(TextStyle.FULL, Locale.getDefault()
on your dayOfWeek instance. More at:
https://github.com/JakeWharton/ThreeTenABP https://www.threeten.org/threetenbp/apidocs/org/threeten/bp/format/TextStyle.html
//selected date from calender
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy"); //Date and time
String currentDate = sdf.format(myCalendar.getTime());
//selcted_day name
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE");
String dayofweek=sdf_.format(myCalendar.getTime());
current_date.setText(currentDate);
lbl_current_date.setText(dayofweek);
Log.e("dayname", dayofweek);
I have the following code that takes a String of milliseconds (will be from an RSS feed so will be a String, the example below is a quick test program) and converts those millis into a Date object.
public static void main(String[] args) {
String ms = "1302805253";
SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(Long.parseLong(ms));
try {
String dateFormat = dateFormatter.format(calendar.getTime());
System.out.println("Date Format = " + dateFormat);
Date dateParse = dateFormatter.parse(dateFormatter.format(calendar.getTime()));
System.out.println("Date Parse = " + dateParse);
} catch (ParseException e) {
// TODO: handle exception
}
}
Output:
Date Format = Fri, 16 Jan 1970 02:53:25 GMT
Date Parse = Fri Jan 16 03:53:25 GMT 1970
As you can see, between the formatting of the calendar object and parsing of the resulting String, an hour is being lost. Also, the formatting of the output has changed. Can anyone help me as to why this is happening, and how to get around it? I want the Date object to be the same format as the "Date Format" output.
I believe it's happening because the UK didn't actually use GMT in 1970, and Java has a bug around that... it will format a date in 1970 as if the UK were using GMT, but without actually changing the offset. Simple example:
Date date = new Date(0);
SimpleDateFormat sdf = new SimpleDateFormat("dd MMM yyyy HH:mm:ss zzz");
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
System.out.println(sdf.format(date));
Result:
01 Jan 1970 01:00:00 GMT
Note that it claims it's 1am GMT... which is incorrect. It was 1am in Europe/London time, but Europe/London wasn't observing GMT.
Joda Time gets this right in that it prints out BST - but Joda Time doesn't like parsing values with time zone abbreviations. However, you can get it to use time zone offets instead:
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) throws Exception {
DateTime date = new DateTime(0, DateTimeZone.forID("Europe/London"));
DateTimeFormatter formatter = DateTimeFormat.forPattern(
"dd MMM yyyy HH:mm:ss Z");
String text = formatter.print(date); // 01 Jan 1970 01:00:00 +0100
System.out.println(text);
DateTime parsed = formatter.parseDateTime(text);
System.out.println(parsed.equals(date)); // true
}
}
The Answer by Jon Skeet is correct.
java.time
Let’s run the same input through java.time to see the results.
Specify a proper time zone name. Never use the 3-4 letter abbreviation such as BST, EST, or IST as they are not true time zones, not standardized, and not even unique(!). So we use Europe/London.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
String input = "1302805253";
long millis = Long.parseLong ( input );
Instant instant = Instant.ofEpochMilli ( millis );
Apply a time zone to produce a ZonedDateTime object.
ZoneId zoneId = ZoneId.of ( "Europe/London" );
ZonedDateTime zdt = instant.atZone ( zoneId );
Dump to console. We see indeed that Europe/London time is an hour ahead of UTC at that moment. So the time-of-day is 02 hours rather than 01 hours. Both represent the same simultaneous moment on the timeline, just viewed through the lenses of two different wall-clock times.
System.out.println ( "input: " + input + " | instant: " + instant + " | zdt: " + zdt );
input: 1302805253 | instant: 1970-01-16T01:53:25.253Z | zdt: 1970-01-16T02:53:25.253+01:00[Europe/London]
Whole seconds
By the way, I suspect your input string represents whole seconds since epoch of 1970 UTC rather than milliseconds. Interpreted that as seconds we get a date in 2011, in the month this Question posted.
String output = Instant.ofEpochSecond ( Long.parseLong ( "1302805253" ) ).atZone ( ZoneId.of ( "Europe/London" ) ).toString ();
2011-04-14T19:20:53+01:00[Europe/London]
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.