How To Convert JavaScript Local Date to UTC And UTC To Local Date

DST is such a pain when it comes to programming. I wish they just get rid of it. It’d be helpful, however, the programmers will still have to deal with the timezones. I was answering questions related to the timers on this website and I keep getting a lot of questions on DST and the timezones. Even though it seems easy, this topic is very confusing. There are lot many sources on the Internet and reading them confuses the hell out of me.

To avoid conflicts when dealing with the transactions from many different timezones, it is essential to normalize the dates and by normalizing I mean converting it to UTC. Let me take an example in JavaScript.

Let the date in question be in Indian Standard Time (IST)

January 02, 2012 22:00:00 GMT+0530



How to convert the date into a local time(CST)?

var now = new Date("January 02, 2012 22:00:00 GMT+0530");
// now = Mon Jan 02 2012 10:30:00 GMT-0600 (CST)



How to convert a date to UTC? This is where many of the online sources go wrong. The simple answer is to convert the date into milliseconds since Epoch and add the timezone offset and convert it back to a date object. Simple? No, this is partially correct. When the calculated milliseconds are converted back to a date, you get a local date.

var nowUtc = new Date( now.getTime() + (now.getTimezoneOffset() * 60000));
//nowUtc = Mon Jan 02 2012 16:30:00 GMT-0600 (CST)



Notice the GMT-0600 (CST) part at the end. That means the resulting date is not GMT, it is CST. If you convert this date to GMT it will read – Mon Jan 02 2012 22:30:00 GMT but we want it to be Mon Jan 02 2012 16:30:00 GMT.

There is also another incorrect way mentioned all over the Internet –

var nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());



The result will be no different than the one that you see above.

How to convert the local date to UTC date?

now.toUTCString()
//now = Mon, 02 Jan 2012 16:30:00 GMT



How to get the local date from the UTC date?

now = new Date(now.toUTCString());
//now = Mon Jan 02 2012 10:30:00 GMT-0600 (CST)



That is a long string to store, is there any alternative to store the UTC time? Just store the number of milliseconds since Epoch converted to UTC by adding the timezone offset.

var millis = now.getTime() + (now.getTimezoneOffset() * 60000)
//millis = 1325543400000



How to convert the milliseconds in UTC to local date? Subtract the timezone offset.

now.setTime(millis - (now.getTimezoneOffset() * 60000))
//now = Mon Jan 02 2012 10:30:00 GMT-0600 (CST)



Let me know if you have any questions or comments.


I just used the below HTML to test the above mentioned code. If you wish, create an HTML file out of it and open it in a browser.

<html>
<body>
<script type="text/javascript">
document.write("IST time - January 02, 2012 22:00:00 GMT+0530");

var now = new Date("January 02, 2012 22:00:00 GMT+0530");
document.write("<br/>IST converted to local time: " + now);

var nowUtc = new Date( now.getTime() + (now.getTimezoneOffset() * 60000));
document.write("<br/>Local time converted to UTC:" + nowUtc);

nowUtc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
document.write("<br/>Local time converted to UTC:" + nowUtc);

document.write("<br/>Local to GMT " + now.toUTCString());

document.write("<br/>GMT to Local " + new Date(now.toUTCString()));

var millis = (now.getTime() + (now.getTimezoneOffset() * 60000));
document.write("<br/>GMT in millis " + millis);

document.write("<br/>Local in millis " + ( millis - (now.getTimezoneOffset() * 60000)));

now.setTime(( millis - (now.getTimezoneOffset() * 60000)));
document.write("<br/>Local from millis " + now);
</script>
</body>
</html>

This code prints the following –
IST time – January 02, 2012 22:00:00 GMT+0530
IST converted to local time: Mon Jan 02 2012 10:30:00 GMT-0600 (CST)
Local time converted to UTC:Mon Jan 02 2012 16:30:00 GMT-0600 (CST)
Local time converted to UTC:Mon Jan 02 2012 16:30:00 GMT-0600 (CST)
Local to GMT Mon, 02 Jan 2012 16:30:00 GMT
GMT to Local Mon Jan 02 2012 10:30:00 GMT-0600 (CST)
GMT in millis 1325543400000
Local in millis 1325521800000
Local from millis Mon Jan 02 2012 10:30:00 GMT-0600 (CST)

Posted in JavaScript | Tagged , , , , , , | Leave a comment

Daylight Saving Time (DST) Should Be A Part of Our History

I was having a conversation with a friend of mine who is convinced that the Daylight Saving Time (DST) change is good and makes perfect sense. I, for one, think that the DST is not useful anymore and it could have been avoided altogether. Just imagine if we didn’t have clocks and a way to time. We would have adjusted out lifestyles automatically to adapt to the nature. Instead of adjusting the clock, we should have adjusted the schedules.

The idea of DST was to save energy and people more social time, but the technology and the lifestyles have changed. The definition of social itself has changed; it’s all online now. With the advanced technology compared to the time when DST was first introduced, the problem with forgetting to spring forward and fall back, the pain it causes to the programmers who deal with the date and time functions, the global workforces and so on, I completely oppose DST.

DST is so last century that it should be a part of history. Definitely not present.

If you think, I could have explained more about DST, don’t worry, someone else already has. Check out the video below. Don’t miss it after 4:30 into the video.

Posted in InterWeb | Tagged , , , , | Leave a comment

Will Google Voice be free in 2012 and beyond?

From the recent notes I made on the Google Voice and how it uses the carrier minutes and data to operate, it should be free in 2012 and beyond.

Why? Currently, Google Voice is not a VOIP service and it uses the carrier minutes and data to operate which means to make or receive calls the subscriber has to pay the carrier. See the image in that post. If Google Voice doesn’t offer VOIP service and starts charging for the voice calls, the subscriber will be double charged. For every call made or received, the subscriber has to pay to use Google Voice and then, since Google Voice uses the carrier minutes, has pay the carrier for using the minutes. If this is exactly how it works, it will be very difficult to justify Google Voice. I’d definitely drop Google Voice and, I think, many other will too.

Charging Google Voice makes sense if either Google Voice offers VOIP services (like Skype which uses just data) or if it charges on a monthly basis – an amount for using their services. The free text messages and the call management service are worth paying for, but if it’s too pricey, one would rather pay the carrier and get rid of call management service. Many plans offer unlimited text messaging ( and do you really need unlimited?) and the call management service isn’t something that one can’t live without. Lo and behold, the biggest benefit would be that you won’t be providing any more self-data to Google than you already have or are.

There are some apps (Talkatone, GrooVe IP etc) which use VOIP services like Google Talk along with Google Voice and allow for free calls over data. What happens if Google decides to get rid of the free calling service in 2012? Even these third party application will not be able to make free calls. The applications will use only data (and save carrier minutes), but Google Voice will not be free. It will be interesting to see what direction those third party applications take at that time.

All this will just be opinions/guesses/rumors, until Google comes out and announces their plan, which should happen not too far from now.

Posted in InterWeb | Tagged , , , , , , , , , , , , , , , , , , | Leave a comment

Does Google Voice Use Minutes or Data?

Does Google Voice Use Minutes or Data? Does Google Voice cost money? How does Google Voice calling or texting work? The answer is Yes, Yes and I don’t know.

Google Voice is an awesome idea and piece of software (if you are willing to give away more self information to Google than you already have). It is not a VOIP service like Google Talk; it is a call management service. It will always cost you money in one way or the other (cellular minutes or data) and you will not be able to make free calls. If you consider cellular data to be free or use wifi, there are workarounds to make it free like using Talkatone or GrooVe IP or other third party apps. These applications use Google Talk free calling feature(VOIP) along with Google Voice, which integrates with Google Talk, to make free calls using only data. Keep in mind that by using more services, you are distributing your own information all over the Internet companies.

Let us recap. Google by itself doesn’t allow free calls on the cellphones. Google allows free calls on the computer using Google Talk. Third party applications allow free calls on the cellphone using the cellular data and Google Voice + Talk.

Are text messages free on Google Voice? Yes. Whether you use it from a cellphone or a computer, messages are free.

But, hey how does Google Voice use your minutes or data to send/make or receive calls/texts? From what I read about it on Google forums, I put together a simple diagram. Notice the color coding in the image.

Google Voice and Carrier Minutes or Data

Incoming and voicemails – Google transfers the call to your cellphone which costs carrier minutes. If you are using Google for voicemail, whenever you miss a call, your carrier forwards the call to Google voicemail. Call forwarding uses carrier minutes.

Outgoing and voicemails – First, if you notice a voicemail and call your voicemail box, you are using carrier minutes. Second, whenever you initiate a outgoing call, Google Voice uses data (a tiny bit) to connect to the server and initiates the call by calling your cellphone, which costs carrier minutes, and then connecting the call to the other phone.

Text message and voicemail – Why is voicemail mentioned here? Because Google transcribes the voicemails which can be accessed as email or text messages. Now, all text messaging happens over the cellular data or wifi and it doesn’t use any cellular minutes.

Oh, why did I say I don’t know how Google Voice works? Because I really don’t know how it works. I just know how they use the carrier minutes/texts (on high level) and I hope by now you do too. Let me know in the comments below.

Note about setup
You are using Google Voice number as primary and transferring calls to your cellphone number.
You have disabled the carrier voicemail and set it to forward to Google Voice voicemail.
You have disabled text message forwarding (to cellphone) on Google Voice.
You have free calls within US/Canada using Google Voice.

Posted in InterWeb | Tagged , , , , , , , , , , , , , , , , , , , , , | Leave a comment

Java: Get Sub List of Elements between two elements (instead of indexes) in a List

Java List APIs provides a way to get the elements (sub-list) in a List between two indexes using List subList(int fromIndex, int toIndex). However, there is no API to get the elements in a List between two list elements List subList(Object fromElement, Object toElement) . The following code is an example to get the elements (sub-list) “between two list elements”. This works even if the given element doesn’t exist in the List. Imagine a list of items with different prices and a sub-list of items between price X and price Y when ,say, there are no items with price X or Y.

The following code, sorts the list and creates a clone just to make sure the original list is unaffected by the method. If the list of items are always expected to be in sorted order, then the clone and sort can be removed. Also, note that this method uses binary search; if the size of the list if small, brute force approach would be efficient than this.

Note that the Item needs compareTo() and equals() override for binary searching and Collection.sort() respectively.

import java.math.BigDecimal;

public class Item implements Comparable<Item> {

 private String name;
 private BigDecimal price;

 @Override
 public int compareTo(Item item) {
  return this.price.compareTo(item.price);
 }

 @Override
 public boolean equals(Object o) {
  return this.price.equals(((Item)o).getPrice());
 }

 @Override
 public String toString() {
  return this.name + " - " + this.price;
 }

 Item(String name, BigDecimal price) {
  setName(name);
  setPrice(price);
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public BigDecimal getPrice() {
  return price;
 }

 public void setPrice(BigDecimal price) {
  this.price = price;
 }
}
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Store {

 // list to hold the items in stock
 private List<Item> itemsInStock;

 public List<Item> getItemsInStock() {
  return itemsInStock;
 }

 public void setItemsInStock(List<Item> itemsInStock) {
  if (this.itemsInStock == null) {
   this.itemsInStock = itemsInStock;
  } else {
   this.itemsInStock.addAll(itemsInStock);
  }
 }

 public void setItemInStock(Item item) {
  if (this.itemsInStock == null) {
   this.itemsInStock = new ArrayList<Item>();
  }
  this.itemsInStock.add(item);
 }

 /**
  * Answers a List of Items from the items in stock between the low price and
  * the high price passed to it. The List returned is <b>backed by</b> the
  * actual items in stock so changes to one are reflected by the other.
  *
  *
  * @param lowPrice
  *            the lowest price of the items to fetch
  * @param highPrice
  *            the highest price of the items to fetch
  *
  * @return a List of Items in stock; null if there are no items between the
  *         lowest and the highest price.
  */
 public List<Item> getItemsInStock(BigDecimal lowPrice, BigDecimal highPrice) {

  // create dummy items for search
  Item startItem = new Item(null, lowPrice);
  Item endItem = new Item(null, highPrice);

  // clone the list so that the ordering of the items in the list is not affected
  List<Item> itemsClone = new ArrayList<Item>(this.itemsInStock);

  // sort the items for binary search
  Collections.sort(itemsClone);

  // Read binary search() documentation for more details.
  int fromIndex = Collections.binarySearch(itemsClone, startItem);
  int toIndex = Collections.binarySearch(itemsClone, endItem);

  // If the low price is not found, get insertion point
  if (fromIndex < 0) {
   // After this, fromIndex will be between ( 0...total items)
   fromIndex = -(fromIndex + 1);
  } else {
   // binary search doesn't necessarily return first matching item
   while (fromIndex > 0 && itemsClone.get(fromIndex).equals(itemsClone.get(fromIndex - 1))) {
    fromIndex--;
   }
  }

  // If the high price is not found, get (insertion point - 1 )
  if (toIndex < 0) {
   // After this, toIndex will be between ( -1...total items-1)
   toIndex = -(toIndex + 2);
  } else {
   // binary search doesn't necessarily return last matching item
   while (toIndex < (itemsClone.size() - 1) && itemsClone.get(toIndex).equals(itemsClone.get(toIndex + 1))) {
    toIndex++;
   }
  }

  /*
   * We have items between start and end ONLY IF fromIndex is <= toIndex
   * and fromIndex is != total items and toIndex is != -1
   */
  if (toIndex < fromIndex) {
   return null;
  }

  // Return a view of the list
  return itemsClone.subList(fromIndex, toIndex + 1);
 }
}
import java.math.BigDecimal;
import java.util.List;

public class Test {

 public static void main(String args[]) {

  Store s = new Store();
  s.setItemInStock(new Item("Nexus S", new BigDecimal(300)));
  s.setItemInStock(new Item("Galaxy S 4G", new BigDecimal(400)));
  s.setItemInStock(new Item("Nexus S 4G", new BigDecimal(400)));
  s.setItemInStock(new Item("Galaxy S2", new BigDecimal(700)));
  s.setItemInStock(new Item("Xperia Arc", new BigDecimal(500)));
  s.setItemInStock(new Item("Sensation 4G", new BigDecimal(600)));
  s.setItemInStock(new Item("Galaxy Nexus", new BigDecimal(750)));
  s.setItemInStock(new Item("iPhone 5", new BigDecimal("799.99")));

  // Get items from Store between 299 and 799
  List<Item> itemsInRange = (List<Item>) s.getItemsInStock(new BigDecimal(299), new BigDecimal(799));

  if (itemsInRange != null) {
   for (Item i : itemsInRange) {
    System.out.println(i);
   }
  } else {
   System.out.println("Sorry, no items found in the price range!");
  }
 }
}

/* OUTPUT for items between 299 & 799
Nexus S - 300
Galaxy S 4G - 400
Nexus S 4G - 400
Xperia Arc - 500
Sensation 4G - 600
Galaxy S2 - 700
Galaxy Nexus - 750
*/
Posted in Java | Tagged , , , , , , , , | Leave a comment