-1

I have a question that I am trying to solve for whole day. I have Date and Time from Oracle DB that is shown on html page. I have jstl date formatter that has special pattern to show it. Let's take an example 09.05.2017 17:35 +0500 and pattern MM.dd.yyyy HH:mm Z. And I am getting it as String with jQuery . The first case: how to convert it to Date type without any changes. I tryed var date = new Date('09.05.2017 17:35 +0500') but if I have another time zone I'll recieve another UTC and time(hour) or maybe month etc. Second: how to convert this time to UTC+0300. I know one solution of this cases, but I think it's not easy. As I have constant pattern of Date, I can always parse the string and to write huge logic for solving second case. I am bad in JS and will be grateful for solution.

  • Maybe you can try this nice Javascript Datetime library: https://momentjs.com/ – oopsdazie Sep 05 '17 at 20:49
  • You should avoid asking more than one distinct question at a time. Regarding parsing, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) Also be cautious with tokens, different parsers use different tokens. – RobG Sep 05 '17 at 20:50

1 Answers1

0

Regarding the parsing question, that is answered at Why does Date.parse give incorrect results? The bottom line is that you should parse the string manually and not rely on the built-in parser. A library can help, but if you only have one or two formats to deal with, writing your own parser isn't too difficult.

As for presenting time in a particular timezone, the same advice applies. If you always want UTC+0300, then start by knowing that javascript Dates are always UTC internally and have UTC methods to access those values. So you just change the UTC time by the required offset and format the date as required.

For formatting, see Where can I find documentation on formatting a date in JavaScript?

An example of adjusting the timezone:

// Return a string for UTC+0300 for the supplied date
// in dd-mm-yyyy hh:mm:ss format
function getUTC03(date) {

  // Helper to pad with leading zero
  function z(n){return ('0'+n).slice(-2)}

  // Copy the date so don't affect original
  var d = new Date(+date);

  // Set UTC time to required offset
  d.setUTCHours(d.getUTCHours() + 3);

  // Format using UTC methods
  return z(d.getUTCDate()) + '-' +
         z(d.getUTCMonth()+1) + '-' +
           d.getUTCFullYear() + ' ' +
         z(d.getUTCHours()) + ':' +
         z(d.getUTCMinutes()) + ':' +
         z(d.getUTCSeconds()) + ' ' +
          '+0300';
}

console.log('Currently at +0300 it\'s ' + getUTC03(new Date()));

However, many places observe daylight saving. To adjust for that, a library is helpful. You just need to provide a location for which the offset can be determined for any particular date and time. Again, there are many questions here about that too.

RobG
  • 142,382
  • 31
  • 172
  • 209