Over a million developers have joined DZone.

Groovy Goodness: Parse Date.toString() Value

DZone's Guide to

Groovy Goodness: Parse Date.toString() Value

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

With Groovy 1.8.4 we can parse the output of the Date.toString() method back to a Date. For example we get the string value of a Date from an external source and want to parse it to a Date object. The format of the string must have the pattern "EEE MMM dd HH:mm:ss zzz yyyy" with the US Locale. This is used by the toString() method of the Date class.

import static java.util.Calendar.*

// Create date 10 November 2011.
def cal = Calendar.getInstance(TimeZone.getTimeZone('Europe/Amsterdam'))
def date = cal.time
date[YEAR] = 2011
date[DATE] = 10

// Get toString() value.
def dateToString = date.toString()
assert dateToString == 'Thu Nov 10 00:00:00 CET 2011'

// Replace Nov for Dec in string and 10 for 24.
dateString = dateToString.replace('Nov', 'Dec').replace('10', '24')

// Use parseToStringDate to get new Date.
def newDate = Date.parseToStringDate(dateString)
assert newDate[MONTH] == DECEMBER
assert newDate[DATE] == 24
assert newDate[YEAR] == 2011


From http://mrhaki.blogspot.com/2011/11/groovy-goodness-parse-datetostring.html

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}