Convert GMT time to specific String Format [duplicate] - java

This question already has answers here:
Illegal pattern character 'T' when parsing a date string to java.util.Date
(4 answers)
Closed 5 years ago.
I have specific case that I must take the date field, convert it to GMT time and then to convert it to specific String format.
This gives the GMT time:
public static void main(String[] args) {
Date rightNow = Calendar.getInstance().getTime();
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(rightNow));
String gmtDate=gmtFormat.format(rightNow);
}
Now I need to that GMT time convert to String format yyyy-MM-ddTHH:mm:ssZ
Example current time in my time zone is 17:10:00, in GMT 15:10:00 so it means final output should be 2017-08-07T15:10:00Z
I tried this code to add:
String pattern = "yyyy-MM-ddTHH:mm:ssZ";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
String date = simpleDateFormat.format(gmtDate);
System.out.println(date);
But of course I am getting the exception because string cannot be converted like this, but I need something similar.

Merge your 2 codeblocks together:
public static void main(String[] args) {
Date rightNow = Calendar.getInstance().getTime();
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
DateFormat gmtFormat = new SimpleDateFormat(pattern);
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(rightNow));
}
Or "yyyy-MM-dd'T'HH:mm:ss.SSSXXX" as per JavaDoc...

Related

issue in converting the date from string to date type

below is the code I have used to add the number of days to the existing date..which gave me string output and I want that to be converted to Date format again...I have tried formating but it gave the out put -->
Date date = sdf.parse(dt);
sysout (date ) --giving me -- Mon May 05 00:00:00 PDT 2008
but I want it as YYYY-MM/DD
sdf.format(date) --Gives me 2008-05-05 which I am looking but it is a string object...but I want this to be converted to DATE type
String dt = "2008-01-01"; // Start date
System.out.println("start date "+dt);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 125); // number of days to add
dt = sdf.format(c.getTime());
System.out.println("c.getTime() "+c.getTime());
System.out.println("end date "+dt);
Date date = sdf.parse(dt);
System.out.println("last but one date in DATE form -->" +date);
System.out.println("last formatted date in string form "+sdf.format(date));
You created the format right.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
but you are using it incorrectly. you should use
sdf.format(your_unformated_date);
Here is a sample code that will convert date from String to Date type using SimpleDateFormat Class:
public static void convert()
{
String str="10:25:35";
SimpleDateFormat sdf=new SimpleDateFormat("hh:mm:ss");
System.out.println(sdf.format(str));
}

How to convert date to numeric calendar date in Java? [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Change date format in a Java string
(22 answers)
Closed 6 years ago.
Wanted to convert the following dates format:
Mar 10th 2016
Mar 1st 2016
Mar 2nd 2016
Mar 3rd 2016
Mar 22nd 2016
into
10-03-2016
01-03-2016
02-03-2016
03-03-2016
22-03-2016
Tried couple of things but failed to get the desired output.
Try string manipulation. Read the input, split based on space and write a logic for your own converter
Try this :)
private String converter (String in) throws Exception {
String stringMonth = in.split(" ")[0];
Date date = new SimpleDateFormat("MMM", Locale.ENGLISH).parse(stringMonth);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int day = Integer.valueOf(in.split(" ")[1].replaceAll("[a-z]", ""));
int year = Integer.valueOf(in.split(" ")[2]) - 1900;
Date result = new Date();
result.setYear(year);
result.setMonth(month);
result.setDate(day);
DateTime dt = new DateTime(result);
return dt.toString("dd-MM-yyyy");
}
As there is no pattern in SimpleDateFormat for ordinal day numbers, you first should clean the string, then parse the date and stringify it back using two SimpleDateFormats:
static final DateFormat DF_FROM = new SimpleDateFormat("MMM d yyyy", Locale.ENGLISH);
static final DateFormat DF_TO = new SimpleDateFormat("dd-MM-yyyy");
synchronized static String convert(String date) throws ParseException {
date = date.replaceAll("(?<=\\d)(st|nd|rd|th)", ""); // remove ordinal suffix
return DF_TO.format(DF_FROM.parse(date)); // convert
}
Please note usage of synchronized for method as SimpleDateFormat methods are not thread-safe.

How can I extract date from since time component [duplicate]

This question already has answers here:
How to convert currentTimeMillis to a date in Java?
(13 answers)
Closed 7 years ago.
I have to extract date in the format MM-dd-yyyy in java from the since time value. Since time is the time at which the doucment is created. For example, if since time is 1452413972759, date would be "Sun, 10 Jan 2016 08:19:32 GMT" (Calculated from http://www.epochconverter.com/) . From this, I could get date in desired format but I am unable to code for the first step i.e., converting since time to date. Can someone help me?
I tried
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date date = df.parse("1452320105343");
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
But it gives parse exception.
Your code can't work because you're trying to parse a number of milliseconds as if it was a MM/dd/yyyy formatted date.
I would have expected the following code to work, where S represents milliseconds :
DateFormat df = new SimpleDateFormat("S");
java.util.Date date = df.parse("1452413972759");
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
However it doesn't for some reason, displaying a date in the 1970 year.
Instead, the following code that parses seconds rather than milliseconds works for your needs :
DateFormat df = new SimpleDateFormat("s");
java.util.Date date = df.parse("1452413972"); // just remove the last 3 digits, or divide by 1000
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));
Or just follow the link from #mohammedkhan and use Date constructor rather than parsing a string :
java.util.Date date = new Date(1452413972759l);
String DATE_FORMAT = "MM/dd/yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
System.out.println("Today is " + sdf.format(date));

convert string to date and time as am/pm format [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
string : 2014-04-25 17:03:13
using SimpleDateFormat is enough to format?
or
otherwise i will shift to any new API?
Date date = new Date(string);
DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
out.println( dateFormat.format (date));
My expected result is (India zone):
Date : 25-04-2014
Time : 05:03 PM
Remembering that Date objects have no inherent format, you need two DateFormat objects to produce the result you seek - one to parse and another to format:
String input = "2014-04-25 17:03:13";
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat outputFormat = new SimpleDateFormat("'Date : 'dd-MM-yyyy\n'Time : 'KK:mm a");
System.out.println(outputFormat.format(inputFormat.parse(input)));
Output:
Date : 25-04-2014
Time : 05:03 PM
Note the use of quoted sequences in the format, such a "'Date : '", which is treated as a literal within the format pattern.
I custom onTimeSet() function . Send the hour and minutes to it. It will return the time with format am and pm
public static String onTimeSet( int hour, int minute) {
Calendar mCalen = Calendar.getInstance();;
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format_local = mCalen.get(Calendar.HOUR);
int hourOfDay_local = mCalen.get(Calendar.HOUR_OF_DAY);
int minute_local = mCalen.get(Calendar.MINUTE);
int ampm = mCalen.get(Calendar.AM_PM);
String minute1;
if(minute_local<10){
minute1="0"+minute_local;
}
else
minute1=""+minute_local;
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
if(hour12format_local==0)
hour12format_local=12;
String selecteTime=hour12format_local+":"+ minute1+" "+ampmStr;
retrun selecteTime;
}
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
more patterns you can find here
Try given below sample code:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
System.out.println(dateFormat.format(date));
//Output: 2013-05-20 10:16:44
For more functionalities on Data and Time try Joda-Time API .

how to convert java string to Date object [duplicate]

This question already has answers here:
Java string to date conversion
(17 answers)
Closed 9 years ago.
I have a string
String startDate = "06/27/2007";
now i have to get Date object. My DateObject should be the same value as of startDate.
I am doing like this
DateFormat df = new SimpleDateFormat("mm/dd/yyyy");
Date startDate = df.parse(startDate);
But the output is in format
Jan 27 00:06:00 PST 2007.
You basically effectively converted your date in a string format to a date object. If you print it out at that point, you will get the standard date formatting output. In order to format it after that, you then need to convert it back to a date object with a specified format (already specified previously)
String startDateString = "06/27/2007";
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate;
try {
startDate = df.parse(startDateString);
String newDateString = df.format(startDate);
System.out.println(newDateString);
} catch (ParseException e) {
e.printStackTrace();
}
"mm" means the "minutes" fragment of a date. For the "months" part, use "MM".
So, try to change the code to:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = df.parse(startDateString);
Edit:
A DateFormat object contains a date formatting definition, not a Date object, which contains only the date without concerning about formatting.
When talking about formatting, we are talking about create a String representation of a Date in a specific format. See this example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateTest {
public static void main(String[] args) throws Exception {
String startDateString = "06/27/2007";
// This object can interpret strings representing dates in the format MM/dd/yyyy
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
// Convert from String to Date
Date startDate = df.parse(startDateString);
// Print the date, with the default formatting.
// Here, the important thing to note is that the parts of the date
// were correctly interpreted, such as day, month, year etc.
System.out.println("Date, with the default formatting: " + startDate);
// Once converted to a Date object, you can convert
// back to a String using any desired format.
String startDateString1 = df.format(startDate);
System.out.println("Date in format MM/dd/yyyy: " + startDateString1);
// Converting to String again, using an alternative format
DateFormat df2 = new SimpleDateFormat("dd/MM/yyyy");
String startDateString2 = df2.format(startDate);
System.out.println("Date in format dd/MM/yyyy: " + startDateString2);
}
}
Output:
Date, with the default formatting: Wed Jun 27 00:00:00 BRT 2007
Date in format MM/dd/yyyy: 06/27/2007
Date in format dd/MM/yyyy: 27/06/2007
try
{
String datestr="06/27/2007";
DateFormat formatter;
Date date;
formatter = new SimpleDateFormat("MM/dd/yyyy");
date = (Date)formatter.parse(datestr);
}
catch (Exception e)
{}
month is MM, minutes is mm..
The concise version:
String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);
Add a try/catch block for a ParseException to ensure the format is a valid date.
var startDate = "06/27/2007";
startDate = new Date(startDate);
console.log(startDate);

Categories

Resources