Java: compare dates using Calendar

When it comes to date comparison most of the times calling the .getTime() method from the Date class is enough.
You can just compare the long variables given from the method.
But there are other cases where you want to compare the year or the month between two dates.
Since the getters and setters from the Date class are deprecated you can not do something like this.

    public void testDate()
    {
        Date date = new Date();
        date.setDate(date.getDate()+1);
        
        System.out.println(date.toString());    
    }

However you can use the Calendar class.


    public void testCalender()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        
        calendar.set(Calendar.YEAR, 1999);
        
        System.out.println(calendar.getTime().toString());
    
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date());
        
        System.out.println(calendar1.getTime().toString());
        
        if(calendar1.get(Calendar.YEAR)>calendar.get(Calendar.YEAR)) {
            System.out.println("You changed the first calendar");
        }
    }

Full test case


import java.util.Calendar;
import java.util.Date;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class DateTest extends TestCase {
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public DateTest( String testName ) {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( DateTest.class );
    }
    
    public void testDate()
    {
        Date date = new Date();
        date.setDate(date.getDate()+1);
        
        System.out.println(date.toString());    
    }
    
    public void testCalender()
    {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        
        calendar.set(Calendar.YEAR, 1999);
        
        System.out.println(calendar.getTime().toString());
    
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(new Date());
        
        System.out.println(calendar1.getTime().toString());
        
        if(calendar1.get(Calendar.YEAR)>calendar.get(Calendar.YEAR)) {
            System.out.println("You changed date one");
        }
    }
}

Spring Jackson and Date Serialization problem

You make a nice restfull api using annotation driven controllers, and jackson mapping until
you discover that the date serialization gives you a timestamp.

This one


@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/mapdate.json",method = RequestMethod.GET)
    @ResponseBody
    public String getJsonDate() {

        Date date = new Date();

        Map map = new HashMap();
        map.put("date",date);

        try {
            return new ObjectMapper().writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        throw new RuntimeException();
    }
}

Gives you this one

{"date":1358897343355}

😦

You can just get away with by changing the mapper configuration.

@Controller
@RequestMapping("/user")
public class UserController {

    @RequestMapping(value = "/mapdate.json",method = RequestMethod.GET)
    @ResponseBody
    public String getJsonDate() {

        Date date = new Date();

        Map map = new HashMap();
        map.put("date",date);

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
            return new objectMapper.writeValueAsString(map);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        throw new RuntimeException();
    }
}

And the world is a better place

{"date":"2013-01-22T23:46:46.236+0000"}

This is a quick one, but since most of us want to have the date format of our choice you can extend the jsonserizalizer or instead of using a date just return a string from a formatted date with the usual DateFormat way.

Joomla component and Json response for ajax requests

Most of the times I want to add some ajax functionality at the Joomla component I am currently developing.

I assume you follow the Joomla component development guide.

You can either do it at the component’s controller.

For example

<?php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import Joomla controller library
jimport('joomla.application.component.controller');

/**
 * Hello World Component Controller
 */
class HelloWorldController extends JController {

    function display(){
        parent::display();
    }

    function testJson() {

        global $mainframe;

        $user = JRequest::getVar("user",null,"get","String");
        $response = array();

        if($user=="gkatzioura"){

            $response["name"] = "Emmanouil";
            $response["surname"] = "Gkatziouras";
        }
        else if($user == null) {
 
            $response["name"] = "Someone";
            $response["surname"] = "Somebody";
        }

        echo json_encode($response);
 
        $mainframe->close();
    }
}

And browse the url http://localhost/joomlasite/?option=com_helloword&task=testJson&user=nothing

Another way is creating a view.ajax.php file.

For example

<?php

defined( '_JEXEC' ) or die( 'Restricted access' );

jimport( 'joomla.application.component.view');

class HelloWorldViewAjax extends JView {

    function display($tpl = null){

       $user = JRequest::getVar("user",null,"get","String");
       $response = array();

       if($user=="gkatzioura"){
           
           $response["name"] = "Emmanouil";
           $response["surname"] = "Gkatziouras";
       }
       else if($user == null) {

           $response["name"] = "Someone";
           $response["surname"] = "Somebody";
       }

       echo json_encode($response);
    }

}

and hit the url http://localhost/joomlasite/?option=com_helloword&view=ajax&format=ajax

Ios + JSON = NSJSONSerialization

Ios 5 provides you with a cool library for json parsing without having to search for
third party libraries.

Here is an example of how to use the NSJSONSerialization class, in order to parse or do some json serialization

//
//  JsonTest.h
//  JsonTest
//
//  Created by gkatzioura on 1/14/13.
//  Copyright (c) 2013 Gkatziouras Emmanouil. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface JsonTest : NSObject
-(NSString*)getjSon;
-(void)parseJson:(NSString*)jsonString;
@end
//
//  JsonTest.m
//  JsonTest
//
//  Created by gkatzioura on 1/14/13.
//  Copyright (c) 2013 Gkatziouras Emmanouil. All rights reserved.
//

#import "JsonTest.h"

@implementation JsonTest
-(NSString*)getjSon {

    NSMutableDictionary* mineDictionary = [[NSMutableDictionary alloc] init];

    [mineDictionary setObject:@"gkatzioura" forKey:@"username"];
    [mineDictionary setObject:@"Gkatziouras" forKey:@"surname"];
    [mineDictionary setObject:@"Emmanouil" forKey:@"name"];

    NSMutableDictionary* yourDictionary = [[NSMutableDictionary alloc] init];

    [yourDictionary setObject:@"dunno" forKey:@"username"];
    [yourDictionary setObject:@"dunno" forKey:@"surname"];
    [yourDictionary setObject:@"dunno" forKey:@"name"];

    NSMutableArray* jsonArray = [[NSMutableArray alloc] init];

    [jsonArray addObject:mineDictionary];
    [jsonArray addObject:yourDictionary];

    NSData* nsdata = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONReadingMutableContainers error:nil];

    NSString* jsonString =[[NSString alloc] initWithData:nsdata encoding:NSUTF8StringEncoding];

    return jsonString;
}

-(void)parseJson:(NSString *)jsonString {

    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

    for(NSDictionary* account in jsonArray) {

        NSLog([account objectForKey:@"username"]);
        NSLog([account objectForKey:@"surname"]);
        NSLog([account objectForKey:@"name"]);
    }

}
@end

And you just do

#import "JsonTest.h"

.
.
.
.

JsonTest* jsonTest = [[JsonTest alloc] init];

NSString* wut = [jsonTest getjSon];

//NSLog(wut);

[jsonTest parseJson:wut];

NSJSONSerialization reference

Ios Phonegap Simple Plugin

You have a Phonegap project, up and running and you want to create a simple plugin.

On your Plugins directory create two files

SimplePlugin.h which contains these lines

#import <Cordova/CDVPlugin.h>
@interface SimplePlugin : CDVPlugin
-(void)sayHello:(CDVInvokedUrlCommand*)command;
@end

and SimplePlugin.c which contains these lines

#import "SimplePlugin.h"

/**
* Gkatziouras Emmanouil 
* Simple phonegap Plugin
*/

@implementation SimplePlugin

-(void)sayHello:(CDVInvokedUrlCommand *)command {
    
    CDVPluginResult* pluginResult = nil;
    NSString* javascript = nil;
   
    //You can choose other statuses for the result such as CDVCommandStatus_ERROR CDVCommandStatus_NO_RESULT and more
    pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"Hello From Phonegap"];
    
    javascript = [pluginResult toSuccessCallbackString:command.callbackId];
    [self writeJavascript:javascript];
}
@end

Now on your javascript file you can call the native code through the Cordova.exec function

Cordova.exec(
                 function(success_parameters) {alert(success_parameters);},
                 function(error_parameters){alert(error_parameters)},
                 "SimplePlugin",
                 "sayHello",
                 ["noparameters"]
                 );

The bad news is that you only have the choice to make async calls to the native code you created.
The first parameter of the function is when the plugin is succesfully called, this means that you used the CDVCommandStatus_OK to send a result. The second parameter is a function when it comes to use the CDVCommandStatus_ERROR status on your native code. The third parameter is the plugin’s name, the forth is the function you want to call. The last parameter is the json data you want to pass to your native function.

Also don’t forget to register your plugin at the Cordova.plist file.

   <dict>
   <key>SimplePlugin</key>
   <string>SimplePlugin</string>
   </dict>

Make a simple jQuery plugin

Let’s say you want to implement a textarea that has a logging nature (this is just an example,of course there are real tools out there for javascript logging 😛 )

You can develop a jquery plugin.
For example

(function( $ ) {
  
    $.fn.AreaLogger = function() {
      
        //assign our element to a variable
        var mytextarea = $(this);
        
        if(this.is("textarea")==false) {
            throw { 
                name:        "Jquery Plugin Error", 
                level:       "Logger Initializaition", 
                message:     "Wrong html Element, please give a textarea.", 
                htmlMessage: "Wrong html Element, please give a textarea." 
            }
        }

        //returning a 'logger' element 
        return {
            info: function(message) {
                mytextarea.val(mytextarea.val()+"INFO "+new Date().toString("dddd, mmmm dS, yyyy, h:MM:ss TT")+": "+message+"\n");
            }
        };
    };
})( jQuery );

On your html code you can just write

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Jquery Plugin Test</title>
        <script src="jquery.min.js">
        </script>        
        <script src="ArreaLogger.js"></script>
        <script>
            $(document).ready(function() {            
                
                var areaLogger = $("#logarea").AreaLogger();
                    
                $("#logtest").click(function() {
                    areaLogger.info($("#test").val());
                });
            });
        </script>
    </head>
    <body>
        <input id="test"/>
        </br>
        <textarea id="logarea"></textarea>
        <div id="wut"></div>
        </br>
        <button id="logtest">Test</button>
    </body>
</html>

You can download jquery from here