Search code examples
datedatetimetimelibgdxformat

How to use date-time utils in libGdx?


I want to use DateTime formatting in my libGdx application, and I want to to be compatible with the web version (gwt). The default java way is not working with the gwt version as the classes needed are not supported.

I already tried using external libraries like joda-time, and treeten-bp. The latter has dependencies to java classes not supported in gwt, and joda-time has dependencies that I could not resolve...

I've seen that gwt has time utils that I need, but I wasn't able to figure out how to use them.

Or even how to add some logic to use normal java utils in android and desktop, and use gwt classes in html5/gwt. But I just can't figure out how to use the gwt classes ie. DateTimeFormat in libGdx. Trying to just import it results in Exception in thread "main" java.lang.NoClassDefFoundError: com/google/gwt/core/client/GWTBridge

Thanks in advance for any help!


Solution

  • You need to use an ActionResolver and implement for each of your module the DateTime method you wish you use (See https://github.com/libgdx/libgdx/wiki/Interfacing-with-platform-specific-code for how to write platform specific code).

    For Android, iOS and Desktop implementation you can use SimpleDateFormat in you ActionResolver.

    For the HTML module, you can use the library

    com.google.gwt.i18n.client.DateTimeFormat 
    

    and implement as follow

        public class HtmlLauncher extends GwtApplication implements com.yourpackage.util.ActionResolver{
    
            @Override
            public GwtApplicationConfiguration getConfig () {
                    return new GwtApplicationConfiguration(360, 640);
            }
    
            @Override
            public ApplicationListener getApplicationListener () {
                    return new MyGame(this);
            }
    
            @Override
            public String convertDate(String format, Date date) {
                DefaultDateTimeFormatInfo info = new DefaultDateTimeFormatInfo();
                DateTimeFormat dateFormat = new DateTimeFormat(format, info) {}; 
    
                return dateFormat.format(date);
            }
    
        }