When you create a JavaScript Date object, it will set the date in your time zone. If you want to keep the same date, but convert it to UTC/GMT for storage and comparison purposes, use the function below: //Converts a Date object to its equivalent in UTC time. function dateToUTC(date) { return new Date(date.getUTCFullYear(), date.getUTCMonth(), […]
How to parse a JSON date with Javascript
Parsing a JSON date is rather easy, and doesn’t even require jQuery. Since the JSON date format is always the same, you can use substr to retrieve the timestamp and parse it to a date. var date = new Date(parseInt(jsonDate.substr(6))); There’s nothing more to it; it’s that easy!
Adding days to a Javascript Date object
Adding an arbitrary amount of days is easy with Javascript. Using the setDays() method, it’s pretty self-explanatory: //Adds a day to today var today = new Date(); var tomorrow = new Date(); tomorrow.setDate(today.getDate()+1); //Tomorrow = today + 1 day
How to isolate the date from a Date object in Javascript
Sometimes, you will need only the date part from a Date object. In order to truncate the time from the date, here is what to do: //Create the date object myDate = new Date(); //Current date and time myDate.setHours(0,0,0,0); //Current date at midnight If you have any questions about JavaScript dates, feel free to ask […]
How to add days to a date in Java
To add years, days, hours or minutes to a Date object in Java, you need to use the java.util.Calendar class. //Adds one day to the current date Calendar cal = Calendar.getInstance(); // The current date cal.add(Calendar.DAY_OF_MONTH, 1); Date date = cal.getTime(); // 1 day in the future If you want to substract time, simply use […]
How to create a Date object for a specific date in Java
Creating a new date in Java is quite simple. Use the Calendar class to quickly create your Date object //Generate a date for Jan. 9, 2013, 10:11:12 AM Calendar cal = Calendar.getInstance(); cal.set(2013, Calendar.JANUARY, 9); //Year, month and day of month Date date = cal.getTime(); If you also need to set the time, you can […]