1

I am trying to get the current date in UTC format in javascript in the following example format:

Thu, Apr 21, 2016

Now I am using Javascript as:

var now = new Date();
var currentDate;
currentDate = now.toUTCString(now);

This returns the date as Thu, Apr 21 2016. Notice the comma after Apr 21. The comma is what I need. Any suggestions would be of great help. Thanks!!

  • 1
    `Notice the comma after Apr 21. The comma is what I need. ` - I do not follow? You mean you want everything but the day of the week? Also why do you want this as in what do you plan on doing with it? If you just want a formatted string for the UI there is a better way to do that. If you want to send it to the server then don't do this at all and use the iso date instead. – Igor Apr 21 '16 at 14:15
  • I want to verify two strings in selenium, Notice the difference between two strings, You will know what I am looking for. :), does that help? – Bishwaroop Chakraborty Apr 21 '16 at 14:17
  • Manipulating dates in javascript is a bit of a cumbersome process (check this post for example http://stackoverflow.com/questions/948532/how-do-you-convert-a-javascript-date-to-utc). Check out this library in case it helps http://momentjs.com/timezone/ – DrinkBird Apr 21 '16 at 14:18
  • 1
    `toUTCString` does not take an argument. – Bergi Apr 21 '16 at 14:23

2 Answers2

1

You could use Moment.js

ref: http://momentjs.com/

Then you can just do:

var dateString = 'Thu, Apr 21, 2016';
var mDate= moment(dateString);
var dateFormatString = 'MMMM, Do, YYYY, h:mm:ss a';
var newDateFormat = mDate.format(dateFormatString);

Check out the formatting options in the ref above.

Hope this helps.

Rhys

Rhys Bradbury
  • 1,699
  • 13
  • 24
0

I recommend DateJS, which will handle many locales/languages. You can give it any custom format string you want. For example, to reproduce what you are asking for:

var now = new Date();
var utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var dateStr = utc.toString("dddd, MMM d, yyyy");

Or as a function (working JSFiddle showing this here):

function formatUTC(d) {
    var utc = new Date(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(),  d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds());
    return utc.toString("dddd, MMM d, yyyy");
}

console.log(formatUTC(new Date()));
Ed Bayiates
  • 11,060
  • 4
  • 43
  • 62