In my app, I have a requirement to format 12 hours time to 24 hours time. What is the method I have to use?
For example, time like 10:30 AM. How can I convert to 24 hours time in java?
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args) throws Exception {
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
Date date = parseFormat.parse("10:30 PM");
System.out.println(parseFormat.format(date) + " = " + displayFormat.format(date));
}
}
which produces:
10:30 PM = 22:30
See: http://download.oracle.com/javase/1.5.0/docs/api/java/text/SimpleDateFormat.html
java.time
In Java 8 and later it could be done in one line using class java.time.LocalTime.
In the formatting pattern, lowercase hh means 12-hour clock while uppercase HH means 24-hour clock.
Code example:
String result = // Text representing the value of our date-time object.
LocalTime.parse( // Class representing a time-of-day value without a date and without a time zone.
"03:30 PM" , // Your `String` input text.
DateTimeFormatter.ofPattern( // Define a formatting pattern to match your input text.
"hh:mm a" ,
Locale.US // `Locale` determines the human language and cultural norms used in localization. Needed here to translate the `AM` & `PM` value.
) // Returns a `DateTimeFormatter` object.
) // Return a `LocalTime` object.
.format( DateTimeFormatter.ofPattern("HH:mm") ) // Generate text in a specific format. Returns a `String` object.
;
See this code run live at IdeOne.com.
15:30
See Oracle Tutorial.
Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H instead of h in the format string.
E.g
HH:mm:ss
instead of
hh:mm:ss
12 to 24 hour time conversion and can be reversed if change time formate in output and input SimpleDateFormat class parameter
Test Data Input:
String input = "07:05:45PM";
timeCoversion12to24(input);
output
19:05:45
public static String timeCoversion12to24(String twelveHoursTime) throws ParseException {
//Date/time pattern of input date (12 Hours format - hh used for 12 hours)
DateFormat df = new SimpleDateFormat("hh:mm:ssaa");
//Date/time pattern of desired output date (24 Hours format HH - Used for 24 hours)
DateFormat outputformat = new SimpleDateFormat("HH:mm:ss");
Date date = null;
String output = null;
//Returns Date object
date = df.parse(twelveHoursTime);
//old date format to new date format
output = outputformat.format(date);
System.out.println(output);
return output;
}
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
provided by Bart Kiers answer should be replaced with somethig like
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a",Locale.UK);
Try This
public static String convertTo24Hour(String Time) {
DateFormat f1 = new SimpleDateFormat("hh:mm a"); //11:00 pm
Date d = null;
try {
d = f1.parse(Time);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DateFormat f2 = new SimpleDateFormat("HH:mm");
String x = f2.format(d); // "23:00"
return x;
}
static String timeConversion(String s)
{
String s1[]=s.split(":");
char c[]=s1[2].toCharArray();
if(s1[2].contains("PM"))
{
int n=Integer.parseInt(s1[0]);
n=n+12;
return n+":"+s1[1]+":"+c[0]+c[1];
}
else``
return s1[0]+":"+s1[1]+":"+c[0]+c[1];
}
It can be done using Java8 LocalTime. Here is the code.
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
public class TimeConversion {
public String timeConversion(String s) {
LocalTime.parse(s, DateTimeFormatter.ofPattern("hh:mm a"));
}
}
And Here is the test case for the same:
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class TimeConversionTest {
#Test
void shouldReturnTimeIn24HrFormat() {
TimeConversion timeConversion = new TimeConversion();
Assertions.assertEquals("22:30", timeConversion.timeConversion("10:30 PM"));
}
}
Using LocalTime in Java 8, LocalTime has many useful methods like getHour() or the getMinute() method,
For example,
LocalTime intime = LocalTime.parse(inputString, DateTimeFormatter.ofPattern("h:m a"));
String outtime = intime.format(DateTimeFormatter.ISO_LOCAL_TIME);
In some cases, First line alone can do the required parsing
This is the extract of code that I have done.
String s="08:10:45";
String[] s1=s.split(":");
int milipmHrs=0;
char[] arr=s1[2].toCharArray();
boolean isFound=s1[2].contains("PM");
if(isFound){
int pmHrs=Integer.parseInt(s1[0]);
milipmHrs=pmHrs+12;
return(milipmHrs+":"+s1[1]+":"+arr[0]+arr[1]);
}
else{
return(s1[0]+":"+s1[1]+":"+arr[0]+arr[1]);
}
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.util.Date;
public class Main {
public static void main(String [] args){
try {
DateFormat parseFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss a");
String sDate = "22-01-2019 9:0:0 PM";
Date date = parseFormat.parse(sDate);
SimpleDateFormat displayFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sDate = displayFormat.format(date);
LOGGER.info("The required format : " + sDate);
} catch (Exception e) {}
}
}
Try this to calculate time difference between two times.
first it will convert 12 hours time into 24 hours then it will take diff between two times
String a = "09/06/18 01:55:33 AM";
String b = "07/06/18 05:45:33 PM";
String [] b2 = b.split(" ");
String [] a2 = a.split(" ");
SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm:ss");
SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm:ss a");
String time1 = null ;
String time2 = null ;
if ( a.contains("PM") && b.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = displayFormat.format(date);
time2 = b2[1];
}else if (b.contains("PM") && a.contains("AM")) {
Date date = parseFormat.parse(a2[1]+" PM");
time1 = a2[1];
time2 = displayFormat.format(date);
}else if (a.contains("PM") && b.contains("PM")){
Date datea = parseFormat.parse(a2[1]+" PM");
Date dateb = parseFormat.parse(b2[1]+" PM");
time1 = displayFormat.format(datea);
time2 = displayFormat.format(dateb);
}
System.out.println(time1);
System.out.println(time2);
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date1 = format.parse(time1);
Date date2 = format.parse(time2);
long difference = date2.getTime() - date1.getTime();
System.out.println(difference);
System.out.println("Duration: "+DurationFormatUtils.formatDuration(difference, "HH:mm"));
For More Details Click Here
I have written a simple utility function.
public static String convert24HourTimeTo12Hour(String timeStr) {
try {
DateFormat inFormat = new SimpleDateFormat( "HH:mm:ss");
DateFormat outFormat = new SimpleDateFormat( "hh:mm a");
Date date = inFormat.parse(timeStr);
return outFormat.format(date);
}catch (Exception e){}
return "";
}
Try this below code,
public static String timeConversion(String s) {
String militaryTime = "";
String hourString = s.substring(0,2);
String timeFormat = s.substring(8,10);
String timeBody = s.substring(2,8);
if (timeFormat.equals("AM")){
if (hourString.equals("12")){
militaryTime = "00" + timeBody;
}else{
militaryTime = hourString + timeBody;
}
}else if (timeFormat.equals("PM")){
if (hourString.equals("12")){
militaryTime = hourString + timeBody;
}else{
int value = Integer.parseInt(hourString) + 12;
militaryTime = String.valueOf(value) + timeBody;
}
}
return militaryTime;
}
Without using library methods
public static String timeConversion(String s) {
String[] timeElements = s.split(":");
if (s.contains("PM")) {
timeElements[0] = getPMHours(timeElements[0]);
} else {
timeElements[0] = getAMHours(timeElements[0]);
}
timeElements[2] = timeElements[2].substring(0,2);
return timeElements[0]+":"+timeElements[1]+":"+timeElements[2];
}
private static String getAMHours(String hour) {
if(Integer.parseInt(hour) == 12) return "00";
return hour;
}
private static String getPMHours(String hour) {
int i = Integer.parseInt(hour);
if(i != 12) return 12+i+"";
return i+"";
}
I was looking for same thing but in number, means from integer xx hour, xx minutes and AM/PM to 24 hour format xx hour and xx minutes, so here what i have done:
private static final int AM = 0;
private static final int PM = 1;
/**
* Based on concept: day start from 00:00AM and ends at 11:59PM,
* afternoon 12 is 12PM, 12:xxAM is basically 00:xxAM
* #param hour12Format
* #param amPm
* #return
*/
private int get24FormatHour(int hour12Format,int amPm){
if(hour12Format==12 && amPm==AM){
hour12Format=0;
}
if(amPm == PM && hour12Format!=12){
hour12Format+=12;
}
return hour12Format;
}`
private int minutesTillMidnight(int hour12Format,int minutes, int amPm){
int hour24Format=get24FormatHour(hour12Format,amPm);
System.out.println("24 Format :"+hour24Format+":"+minutes);
return (hour24Format*60)+minutes;
}
We can solve this by using String Buffer
String s;
static String timeConversion(String s) {
StringBuffer st=new StringBuffer(s);
for(int i=0;i<=st.length();i++){
if(st.charAt(0)=='0' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='0' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '4');
}else if(st.charAt(0)=='0' && st.charAt(1)=='3' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '5');
}else if(st.charAt(0)=='0' && st.charAt(1)=='4' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '6');
}else if(st.charAt(0)=='0' && st.charAt(1)=='5' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '7');
}else if(st.charAt(0)=='0' && st.charAt(1)=='6' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '8');
}else if(st.charAt(0)=='0' && st.charAt(1)=='7' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '1');
st.setCharAt(1, '9');
}else if(st.charAt(0)=='0' && st.charAt(1)=='8' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='0' && st.charAt(1)=='9' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '1');
}else if(st.charAt(0)=='1' && st.charAt(1)=='0' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '2');
}else if(st.charAt(0)=='1' && st.charAt(1)=='1' &&st.charAt(8)=='P' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '2');
st.setCharAt(1, '3');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='A' ){
// if(st.charAt(2)=='1'){
// st.replace(1,2,"13");
st.setCharAt(0, '0');
st.setCharAt(1, '0');
}else if(st.charAt(0)=='1' && st.charAt(1)=='2' &&st.charAt(8)=='P' ){
st.setCharAt(0, '1');
st.setCharAt(1, '2');
}
if(st.charAt(8)=='P'){
st.setCharAt(8,' ');
}else if(st.charAt(8)== 'A'){
st.setCharAt(8,' ');
}
if(st.charAt(9)=='M'){
st.setCharAt(9,' ');
}
}
String result=st.toString();
return result;
}
Related
This question already has answers here:
How to compare dates in Java? [duplicate]
(11 answers)
Closed 5 years ago.
I'm trying to write 'isPast(String dateStr)' function, which receives date string and returns true if it's in the past and false otherwise.
private static boolean isPast(String dateStr) {
Calendar c = GregorianCalendar.getInstance();
int currentYear = c.get(Calendar.YEAR);
int currentMonth = c.get(Calendar.MONTH);
int currentDay = c.get(Calendar.DAY_OF_MONTH);
int currentHour = c.get(Calendar.HOUR_OF_DAY);
int currentMinute = c.get(Calendar.MINUTE);
c.set(currentYear, currentMonth, currentDay, currentHour, currentMinute);
Date now = c.getTime();
SimpleDateFormat sdfDates = new SimpleDateFormat("dd/m/yyyy");
Date date = null;
try {
date = sdfDates.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
if (now.compareTo(date) == 1){
System.out.println(dateStr + " date given is past");
return true;
}
System.out.println(dateStr + " date given is future");
return false;
}
And i'm calling it with:
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
And the output is:
22/04/2018 date given is past
22/01/2018 date given is past
What is going on here? It's not true. I'm on this for too long - it should be simple, obviously i'm missing something with that Calendar object...
Use LocalDate that is available in Java 8
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
System.out.println(isPast(str1));
System.out.println(isPast(str2));
}
private static boolean isPast(String dateStr) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate dates = LocalDate.parse(dateStr, formatter);
return dates.isBefore(LocalDate.now());
}
Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
private static final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
public static void main(String[] args) {
String str1 = "22/04/2018";
String str2 = "22/01/2018";
String str3 = "xx/01/2018";
Date now = new Date();
testDate (str1, now);
testDate (str2, now);
testDate (str3, now);
}
private static void testDate(String str, Date now) {
try {
if (sdf.parse(str).before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (ParseException e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
}
Output:
22/04/2018 is in the future.
22/01/2018 is in the past.
Date not in format dd/MM/yyyy : xx/01/2018
If you have to use Calendar, try this:
private static void testDateUsingCalendar (String str, Date now) {
try {
String[] split = str.split("/");
Calendar c = GregorianCalendar.getInstance();
c.set(Integer.valueOf(split[2]), Integer.valueOf(split[1]), Integer.valueOf(split[0]));
if (c.getTime().before(now)) {
System.out.println(str + " is in the past.");
} else {
System.out.println(str + " is in the future.");
}
} catch (Exception e) {
System.out.println("Date not in format dd/MM/yyyy : " + str);
}
}
I use the code below to see if my input date (format mm/dd/yyyy HH:mm:ss) falls within the range of startDate and endDate.
I use compareTo() in this logic. But with the format mm/dd/yyyy, it compares the month alone and prints output in "MYLOGIC methood". But I need the year to be compared to see if the input date is within startDate and endDate range.
public class DateLogicNew {
public static void main(String[] args) {
String startDate[] = new String[1];
String endDate[] = new String[1];
startDate[0] = "01/01/0600 00:00:00";
endDate[0] = "11/27/3337 00:00:00";
String inputArr[] = { "05/01/0500 01:00:00", "11/27/3337 00:00:00",
"05/05/0700 00:00:00", "11/27/2337 00:00:00",
"06/05/4000 00:00:00" };
String protectedArr[] = new String[inputArr.length];
int temp[] = new int[inputArr.length];
System.out.println(inputArr.length);
System.out.println("Length of the inputArr: " + inputArr.length);
// System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (inputArr[i]
.matches("^([0-1][0-9])/([0-3][0-9])/([0-9]{4})(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
System.out.println("Inside if loop");
if (inputArr[i].compareTo(startDate[0]) > 0
&& inputArr[i].compareTo(endDate[0]) < 0) {
System.out.println("inside the compare condition");
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in MYLOGIC method : "
+ protectedArr[i]);
}
} else {
temp[i] = 0;
}
}
System.out.println("");
for (int i = 0; i < inputArr.length; i++) {
if (temp[i] == 1) {
inputArr[i] = protectedArr[i];
}
System.out
.println("Final Value to the output port: " + inputArr[i]);
}
}
}
java.time
Parse as date-time objects. Regex is overkill.
The modern approach uses the java.time classes rather than the old legacy date-time classes.
String input = "05/01/0500 01:00:00" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MM/dd/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
Compare using methods isBefore, isAfter, isEqual.
if( ( ! x.isBefore( start ) ) && x.isBefore( stop ) ) { … }
I myself figured out the solution for my question. Please check the code below to see the logic before comparing the dates.
String startDate = "0600/01/01 00:00:00";
String endDate = "3337/11/27 00:00:00";
try {
for (int i = 0; i < inputArr.length; i++) {
String newDateInput = inputArr[i];
// System.out.println("NewInput:" + newInput);
DateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
Date convertedDate = parser.parse(newDateInput);
String newFormattedInput = formatter.format(convertedDate);
// System.out.println("newFormattedInput: " +
// newFormattedInput);
if (newFormattedInput
.matches("^([0-9]{4})/([0-1][0-9])/([0-3][0-9])(?:( [0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$")) {
if (newFormattedInput.compareTo(startDate) > 0
&& newFormattedInput.compareTo(endDate) < 0) {
temp[i] = 1;
protectedArr[i] = inputArr[i];
System.out
.println("Values of the inputArr in PROTECT method : "
+ protectedArr[i]);
} else {
temp[i] = 0;
}
}
}
} catch (ParseException e) {
e.printStackTrace();
}
how to get first and last date of weeks on basis of month and year in android
ex:we pass month and year (March,2016) then i want all weeks just like
mar5- mar11,(sat to fri)
mar12- mar18,
mar19- mar25,
mar26-april01
please help me
Call this function to get results in a valid week pair list of given month of a year.
ex: getWeekStartEnd("December","2016");
Result: [
December3-December9,
December10-December16,
December17-December23,
December24-December30
]
List<String> getWeekStartEnd (String month , String year) {
List<String> validWeekPairs = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMMMM-yyyy");
String day = "01";
try {
Date date = sdf.parse(day + "-" + month + "-" + year);
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.setTime(date);
calendar.setFirstDayOfWeek(Calendar.SATURDAY);
List<String> startDayOfWeek = new ArrayList<>();
List<String> endDayOfWeek = new ArrayList<>();
int daysInMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
boolean isStartDaySet = false;
boolean hasLastDayOfWeek = true;
for (int currentDay = 01; currentDay <= daysInMonth; currentDay++) {
Date newDate = sdf.parse(currentDay + "-" + month + "-" + year);
calendar.setTime(newDate);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
if (dayOfWeek == Calendar.SATURDAY) {
if (hasLastDayOfWeek) {
startDayOfWeek.add(month + String.valueOf(currentDay));
isStartDaySet = true;
hasLastDayOfWeek = false;
}
} else if (dayOfWeek == Calendar.FRIDAY) {
if (isStartDaySet) {
endDayOfWeek.add(month + String.valueOf(currentDay));
hasLastDayOfWeek = true;
}
}
}
for (int i = 0; i < endDayOfWeek.size(); i++) {
validWeekPairs.add(startDayOfWeek.get(i) + "-" + endDayOfWeek.get(i));
}
return validWeekPairs;
} catch (ParseException e) {
e.printStackTrace();
return validWeekPairs;
}catch (Exception e){
e.printStackTrace();
return validWeekPairs;
}
}
If you are using java.util.Date you can use the method getDay(). It returns Calendar constant, like Calendar.MONDAY.
You can pass the string as 02,2016
List<String> getWeekendsOftheMonth(String monthYearString) {
long monthDate;
List<String> weekEnds = new ArrayList<>();
SimpleDateFormat simpleDateFormat= new SimpleDateFormat("dd,MM,yyyy");
try {
monthYearString="01,".concat(monthYearString);
monthDate = simpleDateFormat.parse(monthYearString).getTime();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(monthDate);
int maxDate = calendar.getActualMaximum(Calendar.DATE);
int minDate = calendar.getActualMinimum(Calendar.DATE);
for (int i = minDate; i <= maxDate; i++) {
calendar.set(Calendar.DATE, i);
if (calendar.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY|| calendar.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY) {
weekEnds.add(convertToDate(calendar.getTimeInMillis()));
}
}
}catch (Exception e){
e.printStackTrace();
}
return weekEnds;
}
String convertToDate(Long datetime) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM. yyyy");
Date date = new Date(datetime);
return simpleDateFormat.format(date);
}
you can do it from this method.
Used the below code and not getting the exact output.
Desired output:
2015-09-04T11:30:06-0500 to 2015-09-04T11:30:06-05:00
Actual output:
dateValue => 2015-10-19T16:52:23-0400
a => 2015-10-20T02:22:23+0530
My code:
public class test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String a = formattedDate("2015-10-19T16:52:23-0400");
System.out.println ("a => " + a);
}
public static String formattedDate (String dateValue) {
String expectedFormat = "";
SimpleDateFormat inputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat outputDateFormat =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ");
try {
System.out.println("dateValue => " + dateValue);
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(true);
Date d = inputDateFormat.parse(dateValue);
expectedFormat = outputDateFormat.format(d);
} catch (Exception e) {
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
expectedFormat = outputDateFormat.format(cal.getTime());
}
return expectedFormat;
}
}
Under Java 7 and higher, you can use XXX to output the time zone with a column:
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
When you use this to format a data, it will return for example:
2001-07-04T12:08:56-07:00
See the documentation for more examples.
Since I'm using 1.6, XXX is not supported. So used alternative way to achieve this. This is what I did for alternative way..
public static String formattedDate (String dateValue) {
StringBuilder expectedFormat;
SimpleDateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
try {
if (dateValue == null || dateValue.isEmpty()) {
dateValue = "";
}
inputDateFormat.setLenient(false);
Date d = inputDateFormat.parse(dateValue);
} catch (Exception e) {
System.out.println("Error in parsing : " + e.getMessage());
// Sending back the current datetime in the desired format
Calendar cal = Calendar.getInstance();
dateValue = inputDateFormat.format(cal.getTime());
} finally {
expectedFormat = new StringBuilder(dateValue).insert(dateValue.length()-2, ":");
}
return expectedFormat.toString();
}
When you need only the third last character changed and give a string as a parameter how about leaving it a String?
public static String formattedDate (String dateValue)
{
return dateValue.substring(0, dateValue.length() - 2)
+ ":"
+ dateValue.substring(dateValue.length() - 2);
}
Output:
a => 2015-10-19T16:52:23-04:00
I'm able to get current week dates, But How to list previous / next week days ?
This is the method
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
// System.out.println(Arrays.toString(days));
return days;
}
pls see the image, and tell me how to get the next and previous week days
finally i got the answer pls see this
Get the present Week:
public String [] getWeekDay()
{
Calendar now = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the Next Week:
int weekDaysCount=0;
public String [] getWeekDayNext()
{
weekDaysCount++;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
Get the previous Week:
public String [] getWeekDayPrev()
{
weekDaysCount--;
Calendar now1 = Calendar.getInstance();
Calendar now = (Calendar) now1.clone();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String [] days = new String[7];
int delta = -now.get(GregorianCalendar.DAY_OF_WEEK) + 1;
now.add(Calendar.WEEK_OF_YEAR , weekDaysCount);
now.add(Calendar.DAY_OF_MONTH , delta);
for (int i = 0; i < 7; i++)
{
days [i] = format.format(now.getTime());
now.add(Calendar.DAY_OF_MONTH , 1);
}
return days;
}
to assign the textView
NextPreWeekday = getWeekDay();
firstDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [0]);
lastDayOfWeek = CommonMethod.convertWeekDays(NextPreWeekday [6]);
textViewDate.setText(firstDayOfWeek + "-" + lastDayOfWeek + " " + CommonMethod.convertWeekDaysMouth(NextPreWeekday [6]));
textViewSun.setText(CommonMethod.convertWeekDays(NextPreWeekday [0]) + "\nSun");
textViewMon.setText(CommonMethod.convertWeekDays(NextPreWeekday [1]) + "\nMon");
textViewTue.setText(CommonMethod.convertWeekDays(NextPreWeekday [2]) + "\nTue");
textViewWed.setText(CommonMethod.convertWeekDays(NextPreWeekday [3]) + "\nWeb");
textViewThu.setText(CommonMethod.convertWeekDays(NextPreWeekday [4]) + "\nThu");
textViewFri.setText(CommonMethod.convertWeekDays(NextPreWeekday [5]) + "\nFri");
textViewSat.setText(CommonMethod.convertWeekDays(NextPreWeekday [6]) + "\nSat");
public static String convertWeekDays(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("dd");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
public static String convertWeekDaysMouth(String date)
{
String formattedDate = null;
try
{
SimpleDateFormat originalFormat = new SimpleDateFormat("yyyy-MM-dd" , Locale.ENGLISH);
SimpleDateFormat targetFormat = new SimpleDateFormat("MMM yyyy");
Date date12 = originalFormat.parse(date);
formattedDate = targetFormat.format(date12);
} catch (Exception e)
{
e.printStackTrace();
}
return formattedDate;
}
For current week.
SimpleDateFormat displayDate = new SimpleDateFormat("dd-MMM-yyyyy"));
final Calendar calenderThisWeek = Calendar.getInstance();
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderThisWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
For Previous Week
final Calendar calenderpreviousWeek = Calendar.getInstance();
calenderpreviousWeek.add(Calendar.DAY_OF_WEEK, -1);
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderThisWeek.getTime()); // dd-mmm-yyyy
calenderpreviousWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderpreviousWeek.getTime()); // dd-mmm-yyyy
For Next Week
final Calendar calenderNextWeek = Calendar.getInstance();
calenderNextWeek.add(Calendar.DAY_OF_WEEK, +1);
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
String strWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy
calenderNextWeek.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
String endWek = displayDate.format(calenderNextWeek.getTime()); // dd-mmm-yyyy