Set a String variable to a Date object in java - java

I want to set a hand written String as the date for a Date object. What I'm trying to say is that I want to do is this:
String date= [date string here!!!];
Date mydate = new Date(date);
Something like that. The reason I want to do this is because I want my network to have standard Date and Time because since I run them from the same machine the time is being taken from the same clock and it gets different time every time. So I want to get that time and also add 1-2 seconds in the end so I can test my nodes with different times.

Java is strongly typed language. You cannot assign string to Date. However you can (and should) parse string into date. For example you can use SimpleDateFormat class like the following:
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse("2013-05-06");

you'll want to use dateformatter
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date date = formatter.parse("01/29/02");

String string = "January 2, 2010";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010
updated
String string ="2013-04-26 08:34:55.705"
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").parse(string);
System.out.println(date);

Related

Change date from MM/dd to yyyy-MM-dd'T'HH:mm:ss.SSZ in Java

I have a String that formatted MM/dd. I would like to convert it to a Date in format yyyy-MM-dd'T'HH:mm:ss.SSZ.
DateFormat df = new SimpleDateFormat("MM/dd");
String strDate = "06/05";
Date date = new Date();
date = df.parse(strDate);
This makes it a Date, but in the original format.
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSZ").format(date));
This returns the correct month and day, but nopthing else.
1970-06-05T00:00:00.00-0400
Any idea how I can make it return
CURRENT_YEAR-06-05TCURRENT_TIME
In the question, the date format pattern indicates a desire for 2-digit fractional seconds. SimpleDateFormat cannot do that.
The newer Java 8 Time API can, and you should be using that anyway.
If you're running on Java 6 or 7, get the ThreeTen-Backport library.
To parse a MM/dd formatted string and get a full timestamp with current year and time-of-day, in the default time zone, use the following code:
String strDate = "06/05";
MonthDay monthDay = MonthDay.parse(strDate, DateTimeFormatter.ofPattern("MM/dd"));
ZonedDateTime date = ZonedDateTime.now().with(monthDay);
System.out.println(date.format(DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSZ")));
Sample Output
2020-06-05T14:52:48.45-0400
I recommend to make use of java.time package. There you go:
var ds = "01/12";
var df = java.time.format.DateTimeFormatter.ofPattern("MM/dd");
var dt = java.time.MonthDay.from(df.parse(ds)).adjustInto(java.time.LocalDateTime.now());
Then you can convert dt to java.util.Date or whatever you like. Or simply use one of java.time formaters to get the desired output.
You are creating a date with only month and day
If you want to use the current year and time, you can create a calendar object and edit the month and day
For something this simple I suggest a different approach, get current time then set month and day from the original string THEN format.
String str = "08/09";
String[] split = str.split("/");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(split[0]));
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(split[1]));
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").format(calendar.getTime()));
String strDate = "06-05";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-"+strDate+"'T'HH:mm:ss.SSZ");
System.out.println(sdf.format(new Date()));
the output:
2020-06-05T23:00:45.306+0400

Convert TextField into Date

I want to convert TextField into Date.
private TextField fieldDateAgentAdded;
Date dateAgentAdded;
dateAgentAdded(fieldDateAgentAdded.toString())
Can you tell me how I can convert the String into Date?
Well you can do it in one line using:
dateAgentAdded(new SimpleDateFormat("dd/MM/yy", Locale.ENGLISH).parse(fieldDateAgentAdded.toString());
There is thousand of way to write date, so you don't really have choice, you need to specify the expected format.
You can use SimpleDateFormat class.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = DATE_FORMAT.parse("2013-12-4");
System.out.println(date.toString());
The easiest way is to use the SimpleDateFormat class. Here is an example:
String dateString = "May 14, 2012";
Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(dateString);
Now date should contain the date May 14, 2012. For more information see the javadoc.

convert a date object to Oracle timestamp type string

I want to convert a date object, ex: new Date(), to a string which has a format like Oracle's time stamp type, ex: 21-OCT-13 11.08.13.858000000 AM. I know I could just get each piece of information in the date object like day, month, year, hour, minute, ... to form the Oracle format string but I really want to know is there a utility to do that instead?
Using SimpleDateFormat#format() you would print a Date as
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS a");
System.out.println(sdf.format(new Date()).toUpperCase());
Output :
21-OCT-13 10.01.38.000000614 AM
See JavaDocs for Date and Time patterns.
Try taking a look at SimpleDateFormats - That would be your best bet and easiest way of doing it.
Eg:
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); //Hours:Minutes:Seconds
String strDate = dateFormat.format(date);
Use SimpleDateFormat.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("your_format_here"); // dd/MM/yy h:mm:ss a
String formattedDate = sdf.format(date);
System.out.println(formattedDate);

Calender issue with time zone

I'm having a weird situation with Java Calendar. I'm using dozer mapper to map the objects.
I want to write a method that will convert this object to the following format. yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
say element 2010-11-11T09:30:47.000Z
public Calender getValue(Date source,Calender c) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
calendar.setTime(source);
return calendar;
}
When I run the program, it is printing
2010-11-11T04:00:47.000Z - Because we are setting the Timezone to be GMT, (9.30 - 5.30 = 4.00)
I want my object to have same format and value.if I don't set TimeZone to GMT, it will show as 2008-11-21T09:30:47.000+05:30.
I want it as 2010-11-11T09:30:47.000Z.
I tried added 5.30 to calender.
calendar.add(Calendar.HOUR, 5);
calendar.add(Calendar.MINUTE, 30)
then it works.But if this is ran from any other place, difference won't be 5.30.So I cannot add 5.30 to calenderget
Is there any way to get rid of this problem? I want to return Calender object.
Any suggestions or help would be much appreciated
Use a pattern. F.E:
String pattern = "yyyy-MM-dd'T'HH:mm:ssZ";
DateTimeFormatter dtf = DateTimeFormat.forPattern(pattern);
Also,
SimpleDateFormat dateformatyyyyMMdd = new SimpleDateFormat("yyyyMMdd");
String date_to_string = dateformatyyyyMMdd.format(dateNow);
you can use SimpleDateFormat like this.
SimpleDateFormat formatter, FORMATTER;
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String oldDate = "2011-03-10T11:54:30.207Z";
Date date = formatter.parse(oldDate.substring(0, 24));
FORMATTER = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.SSS");
System.out.println("OldDate-->"+oldDate);
System.out.println("NewDate-->"+FORMATTER.format(date));
Output OldDate-->2011-03-10T11:54:30.207Z NewDate-->10-Mar-2011 11:54:30.207

Date converter in JAVA [duplicate]

This question already has answers here:
How to parse a date? [duplicate]
(5 answers)
Closed 9 years ago.
I have date like Tue Mar 19 00:41:00 GMT 2013, how to convert it to 2013-03-19 06:13:00?
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = bdate;
Date ndate = formatter.parse(formatter.format(date));
System.out.println(ndate);
gives the same date.
Use two SimpleDateFormat objects with appropriate formats and use the first to parse the string into a date and the second to format the date into a string again.
As the first answer says. First parse your date with SimpleDateFormat like this:
Date from = new SimpleDateFormat("E M d hh:mm:ss z yyyy").parse("Tue Mar 19 00:41:00 GMT 2013");
Then use that to format the resulting date object with another instance of SimpleDateFormat like this:
String to = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(from);
See the javadoc of SimpleDateFormat here. Hope that helps.
One major thing that the others have left out is dealing with the timezone (TZ). Anytime you use a SimpleDateFormat to go to/from a string representation of the date, you really need to be aware of what TZ you're dealing with. Unless you explicitly set the TZ on the SimpleDateFormat, it will use the default TZ when formatting/parsing. Unless you only deal with date strings in the default timezone, you'll run into problems.
Your input date is representing a date in GMT. Assuming that you also want the output to be formatted as GMT, you need to make sure to set the TZ on the SimpleDateFormat:
public static void main(String[] args) throws Exception
{
String inputDate = "Tue Mar 19 00:41:00 GMT 2013";
// Initialize with format of input
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
// Configure the TZ on the date formatter. Not sure why it doesn't get set
// automatically when parsing the date since the input includes the TZ name,
// but it doesn't. One of many reasons to use Joda instead
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = sdf.parse(inputDate);
// re-initialize the pattern with format of desired output. Alternatively,
// you could use a new SimpleDateFormat instance as long as you set the TZ
// correctly
sdf.applyPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
}
Use SimpleDateFormat in this way:
final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
final Date date = new Date();
System.out.println(formatter.format(date));
If you do any calculations or parsing with dates please use JodaTime because the standard JAVA date support is really buggy

Categories

Resources