How to Convert Hard Coded date into standard GMT format - javascript

I need to convert a hard coded date into a standard GMT format.How can I do this?
The date I have is in the following format:
var myDate = 'dd|mm|yyyy';
There is no time or day description in the date.Just the 'dd|mm|yyyy' string.
Is there a way I can convert it into GMT?
Thanks in advance.

a = '22/02/2014'.split('/')
d = new Date(a[2],parseInt(a[1], 10) - 1,a[0])
//Sat Feb 22 2014 00:00:00 GMT+0530 (India Standard Time)
Now you have a javascript date object in d
utc = d.getUTCDate() + "/" + (d.getUTCMonth() + 1 ) + "/" + d.getUTCFullYear();
//"21/2/2014" for an accurate conversion to UTC time of day is a must.
If you are in say India, the Javascript Date object will have timeZoneOffset 330. So its not possible to keep a javascript Date object with timezone GMT unless your system time is GMT.
So if you want a Date object for calculation, you can create one with localTimezone and simply suppose it is GMT
pseudoGMT = new Date( Date.parse(d) + d.getTimezoneOffset() * 60 * 1000);
//Fri Feb 21 2014 18:30:00 GMT+0530 (India Standard Time)
If you can explain your high level requirement we might be able to help with some alternate solutions.

Use regex matching to extract the data you need:
var myDate = "21|01|2014";
var data = myDate.match(/(\d{2})\|(\d{2})\|(\d{4})/);
var date = new Date(data[3], data[2] - 1, data[1]);
Note that the month is 0-indexed, so january = 0
More on regular expressions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Related

get the current date from GMT

I want to get the date from the GMT time but it returns the date which is one day ahead. How can I get the date mentioned in the GMT string always?
new Date("Mon, 27 Aug 2018 22:00:00 GMT").getDate()
This command returns 28 as the output, but I want 27.
Is there anything I need to add?
Thanks in advance.
Try this One.I think your problem will be solved.
<script>
function myFunction() {
var d = new Date();
var n = d.getUTCDate();
document.getElementById("demo").innerHTML = n;
}
</script>
When you create a new Date() the browser returns date based on your device timezone. You can use Date.getTimezoneOffset() to get GMT offset time difference and then adjust the time by multiplying the value.
// Your date
var myDate = new Date("Mon, 27 Aug 2018 22:00:00 GMT")
// Convert your date to local using getTimezoneOffset() and multiply with 60000 to get time adjusted GMT 0
var myDateLocal =new Date( myDate.valueOf() + myDate.getTimezoneOffset() * 60000 ).getDate();
document.getElementById("myDate").innerHTML=myDateLocal;
<h1 id="myDate" ></h1>

javascript similar Date objects, return defferent epochs?

when i use different Date constructors i receive similar Date objects but when i get there epoch values they have slightly different values.
Is it a bug or something or i'm just passing wrong value formats into constructors?
> date1 = new Date();
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date2 = new Date(date1.toString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date3 = new Date(date1.toISOString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date1.getTime();
1443960093117
> date2.getTime();
1443960093000
> date3.getTime();
1443960093117
I'm using node(v0.12.2) in Ubuntu 14.04.1.
Apparently date1.toString() does not take the milliseconds into account while date1.toISOString() does. Yes, this is not a bug, you're just passing different strings. For me:
var date1 = new Date();
console.log(date1.toString(), date1.toISOString())
// Sun Oct 04 2015 14:54:37 GMT+0200
// 2015-10-04T12:54:37.113Z
The ISO date format includes a field to represent a fractional part of a second. The default date format doesn't, and when a default date format is parsed the system assumes the second value is exact.
> new Date().toString()
'Sun Oct 04 2015 07:53:48 GMT-0500 (CDT)'
> new Date().toISOString()
'2015-10-04T12:53:58.769Z'
In the ISO string, .769 is the seconds fraction part.
When you just log a date it automatically uses the default method .toString() version which drops the milliseconds. Using the below code you can see that the .###Z is dropped for .toString() but not for .toISOString() because it is in the extended ISO format.
var date1 = new Date();
var date2 = new Date(date1.toString());
var date3 = new Date(date1.toISOString());
console.log('date1 ' + date1.toISOString());
console.log('date2 ' + date2.toISOString());
console.log('date3 ' + date3.toISOString());
console.log('date1 ' + date1.getTime());
console.log('date2 ' + date2.getTime());
console.log('date3 ' + date3.getTime());
Which returns
date1 2015-10-04T13:34:37.778Z
date2 2015-10-04T13:34:37.000Z
date3 2015-10-04T13:34:37.778Z
date1 1443965677778
date2 1443965677000
date3 1443965677778
Hopefully this helps.

Remove time from GMT time format

I am getting a date that comes in GMT format, Fri, 18 Oct 2013 11:38:23 GMT. The problem is that the time is messing up the timeline that I am using.
How can I strip out everything except for the actual date?
If you want to keep using Date and not String you could do this:
var d=new Date(); //your date object
console.log(new Date(d.setHours(0,0,0,0)));
-PS, you don't need a new Date object, it's just an example in case you want to log it to the console.
http://www.w3schools.com/jsref/jsref_sethours.asp
Like this:
var dateString = 'Mon Jan 12 00:00:00 GMT 2015';
dateString = new Date(dateString).toUTCString();
dateString = dateString.split(' ').slice(0, 4).join(' ');
console.log(dateString);
I'm using this workaround :
// d being your current date with wrong times
new Date(d.getFullYear(), d.getMonth(), d.getDate())
You could use Moment.js, a library that provides many helper functions to validate, manipulate, display and format dates and times in JavaScript.
Using Moment.js lib:
var dateString = new Date('Mon Jan 12 00:00:00 GMT 2015');
moment(dateString).format('YYYY-MM-DD HH:mm');
Or simplified:
moment('Mon Jan 12 00:00:00 GMT 2015').format('YYYY-MM-DD HH:mm')
Well,
Here is my Solution
let dateString = 'Mon May 25 01:07:00 GMT 2020';
let dateObj = new Date(dateString);
console.log(dateObj.toDateString());
// outputs Mon May 25 2020
See its documentation on MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
Just cut it with substring:
var str = 'Fri, 18 Oct 2013 11:38:23 GMT';
str = str.substring(0,tomorrow.toLocaleString().indexOf(':')-3);
In this case you can just manipulate your string without the use of a Date object.
var dateTime = 'Fri, 18 Oct 2013 11:38:23 GMT',
date = dateTime.split(' ', 4).join(' ');
document.body.appendChild(document.createTextNode(date));
You can first convert the date to String:
String dateString = String.valueOf(date);
Then apply substring to the String:
dateString.substring(4, 11) + dateString.substring(30);
You need to take care as converting date to String will actually change the date format as well.

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Javascript: Extract a date from a string?

I have a string formatted as either
Today 3:28AM
Yesterday 3:28AM
08/22/2011 3:28AM
What I need to do is somehow extract into a variable the date portion of my string, ie. 'Today', 'Yesterday' or a date formatted as DD/MM/YYYY.
Is something like this possible at all with Javascript?
Since the JavaScript date parser won't recognize your dates, you can write a parser that puts the date into a format that it will recognize. Here is a function that takes the date examples that you gave and formats them to get a valid date string:
function strToDate(dateStr) {
var dayTimeSplit = dateStr.split(" ");
var day = dayTimeSplit[0];
var time = dayTimeSplit[1];
if (day == "Today") {
day = new Date();
} else if (day == "Yesterday") {
day = new Date();
day.setDate(day.getDate() - 1);
} else {
day = new Date(day);
}
var hourMinutes = time.substring(0, time.length -2);
var amPM = time.substring(time.length -2, time.length);
return new Date((day.getMonth() + 1) + "/" + day.getDate() + "/" + day.getFullYear()
+ " " + hourMinutes + " " + amPM);
}
Then you can call stroToDate to convert your date formats to a valid JavaScript Date:
console.log(strToDate("Today 3:28AM"));
console.log(strToDate("Yesterday 3:28AM"));
console.log(strToDate("08/22/2011 3:28AM"));
Outputs:
Sun Sep 25 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Sat Sep 24 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Mon Aug 22 2011 03:28:00 GMT-0700 (Pacific Daylight Time)
Obviously "Today" and "Yesterday" can never be transformed back to a real numeric date, for now it seems that what are you trying to do here is to save it as "Today" and "Yesterday", right?
It appears that the dd/mm/yyyy hh:mmxx you specified is always separated by a space.
so you can just split the string into two, and save the first part as your date.
the javascript function:
http://www.w3schools.com/jsref/jsref_split.asp
As for how to transform from "Today" back to 26/09/2011 etc, you need to seek solution from the XML side.
Here is a similar question: Javascript equivalent of php's strtotime()?
Here is the linked article: http://w3schools.com/jS/js_obj_date.asp
And the suggested solution:
Basically, you can use the date constructor to parse a date
var d=new Date("October 13, 1975 11:13:00");
There are a couple of ways you could do this. I will offer 2 of them.
option1:
If the day always at the beginning of the string you could capture the the first part by using a regular expression like /([a-z0-9]*)\s|([0-9]{1,})\/([0-9]{1,})\/([0-9]{1,})\s/ <- im not the best regex writer.
option2:
You could also do a positive look ahead if the time come immediately after the day (like your example above. Here is a link with the proper syntax for JS regex. http://www.javascriptkit.com/javatutors/redev2.shtml you can scroll down to lookaheads and see an example that should get you suared away there.
var reTYD = /(today|yesterday|\d{1,2}\/\d{1,2}\/\d{4})/i;
console.log( myString.match(reTYD) );

Categories