I've got this string 21-04-2016 for instance, that I'm trying to convert to a date. After that's done I need to flip it around, remove all the dashes and then convert it back to a string so that it looks like 20160421. I have found some code that I'll post below but I want to know if there is a simple way of doing this, maybe without having to convert the string to a date? Anyhow, here's my (broken) code:
String from = region.startDate //I get this string from a controller
Date fromDate = Date.parse('yyyy-MM-dd', from) //.parse is depricated apparently
println(from)
println(fromDate)
Here's what I get back (from the println):
Wed Jul 08 00:04:00 SAST 16
11-04-2016
No need to convert from String to Date in that case (you could use a SimpleDateFormat (or rather two) to do that, though); just use String and List operations from Java and Groovy:
from.split('-').reverse().join()
Related
I wanted to change time at date type which returning from mongodb with custom time like below
"2021-05-26T00:00:00.000Z"
to
"2021-05-26T10:20:00.000Z"
I wanted to change time from a variable at the date, so my technique was split this date with "T" then get time part and change it with custom time
let splitedTime = timev[0].validFrom.toString().split()[0];
let customTime = "10:20:00.000Z";
let finalTime = splitedTime + customTime;
but this split not working this giving me date like this "Wed May 26 2021 06:00:00 GM". Can you please help me for this?
Working with Date
Whilst I understand your logic of converting it to a string and then using string methods to convert it to your desired output, I believe a simpler approach is to use the Date object
function dateAdd(original, hours, minutes) {
const date = new Date(original);
date.setHours(original.getHours() + hours);
date.setMinutes(original.getMinutes() + minutes);
return date.toISOString();
}
When original = "2021-05-26T00:00:00.000Z" then the return value is "2021-05-26T10:20:00.000Z".
If you want a fixed time:
const date = new Date('2021-05-26T00:00:00.000Z');
date.setUTCHours(10);
date.setUTCMinutes(20);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
// a cleaner approach:
date.setUTCHours(10, 20, 0); // hoursValue, minutesValue, secondsValue
console.log(date.toISOString());
Which produces the following:
"2021-05-26T10:20:00.000Z"
Another Solution
Your actual problem is being caused by the fact you call toString which returns a date string in the format of "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" so when you're splitting by "T", that's way down at the end. toISOString will return the correct format.
Explanation
As you can see above, we avoid using string methods and use the methods that exist on Date. This approach is safer as you avoid issues with the difference between toISOString and toString. You may also find moment useful if you're using dynamic methods of changing dates regularly.
Note
In all honesty, I'm not entirely sure I understand the why behind what you're doing, so if I'm wrong please correct me so I can update my answer to be more relevant for you.
Learn More
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
With the following code:
def date = new Date()
println new groovy.json.JsonBuilder([(date): date]).toString()
The result is something like
{"Fri Oct 28 15:00:45 ART 2016":"2016-10-28T18:00:45+0000"}
I was expecting the same representation as key and as value for the same date.
Can I force the JsonBuilder to output the keys with the same format as the values?
Thing is, JsonBuilder will format dates using by default a new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") and I understand this is not what you wish to change. Since the "key" part is serialized with the toString() method, you have two solutions: either use [date.format("yyyy-MM-dd'T'HH:mm:ssZ"): date] or use metaProgramming to overload Date.toString() (it will be used for every Date object, though, so you might not want that).
I'm want to query for an object in my CoreData using NSDate.
I have an string like "2013:32:17 06:32:24 -0300".
When I get the object and convert it using "[format setDateFormat:#"yyyy:mm:dd hh:mm:ss ZZZ"]" I get a string like "2013:32:17 09:32:24 +0000"
How do I convert to the same original format above (-0300 ???)
Tk's!!
I am working with SoupUI a i need to adjust a Date/time (UTC) that i get back in a response to a GMT Date/time. The date that i get back in the respone looks as followes:
2012-11-09T00:00:00+01:00
I would like to convert this to
2012-11-08T23:00:00Z
Unfortunatly i lack Java skils and therefore also Groovy skils to be able to do this on my own. i did a lot o searches on date convertions but until now i was still unable to find what i was looking for. i will keep searching. if i do manage to get the solution then i will post it here.
Assuming there isn't a colon in the timezone portion, I believe this should work:
// Your input String (with no colons in the timezone portion)
String original = '2012-11-09T00:00:00+0100'
// The format to read this input String
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssZ" )
// The format we want to output
def outFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss'Z'" )
// Set the timezone for the output
outFormat.timeZone = java.util.TimeZone.getTimeZone( 'GMT' )
// Then parse the original String, and format the resultant
// Date back into a new String
String result = outFormat.format( inFormat.parse( original ) )
// Check it's what we wanted
assert result == '2012-11-08T23:00:00Z'
If there is a colon in the TimeZone, you'll need Java 7 for this task (or maybe a date handling framework like JodaTime), and you can change the first two lines to:
// Your input String
String original = '2012-11-09T00:00:00+01:00'
// The format to read this input String (using the X
// placeholder for ISO time difference)
def inFormat = new java.text.SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssX" )
I am trying to save data into my database using a vb form. I am using a datetimepicker to insert the date into my database. Here's an example
saveCommand.Parameters.AddWithValue("A_BOOKDATE", abookdatePicker1.Text).DbType = DbType.DateTime
In my database i set its attribute to time ,now the thing is i used the same line of code on another database and it worked but this one is giving this error
'Failed to convert parameter value from string to datetime'
How do i convert this string to datetime.
Many Thanks
Use DateTimePicker.Value instead of DateTimePicker.Text:
saveCommand.Parameters.AddWithValue("A_BOOKDATE", abookdatePicker1.Value) _
.DbType = DbType.DateTime
(If you ever actually have to convert a string to a DateTime, use DateTime.TryParseExact or DateTime.ParseExact, but in this case it's better not to use the string representation at all.)
You could also try to use
Convert.ToDateTime Method (String) (this one will return a datatime object or throw and exception)
DateTime.TryParse Method (String, DateTime) (this one returns the datetime as an output parameter, returns null on failure)