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) );
Related
This works:
var myDateString = '19th sep 2015';
myDateString = myDateString.replace('st','');
myDateString = myDateString.replace('th','');
myDateString = myDateString.replace('nd','');
myDateString = myDateString.replace('rd','');
var date = new Date(myDateString);
But is there a cleaner way? Can I pass the date format (including the ordinal part) to the Date constuctor?
I wouldn't rely on it parsing correctly for all people - for instance, people in France might have their locale set to French (surprise) and that would fail to parse apr for instance, because for them it's avr.
Instead, parse it yourself:
var myDateString = '19th sep 2015';
var parts = myDateString.split(" ");
var date = parts[0].replace(/\D/g,''); // keep only numbers
var month = "janfebmaraprmayjunjulaugsepoctnovdec".indexOf(parts[1].toLowerCase())/3;
var year = parts[2];
var date = new Date(year, month, date);
// note because of how we got the month, it's already conveniently zero-based
Use Moment.js library and use your date string like this:
moment('19th sep 2015', 'Do MMMM YYYY').format("D MMMM YYYY")
Output:
"19 September 2015"
The easiest way is to use a library like moment.js or the date part of sugar.js.
To do this properly by hand is not fun.
Update
If you're in full control of the dates, just use ISO 8601 date format, which the constructor of Date understands in any browser.
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
This question already has answers here:
How to add days to Date?
(56 answers)
Closed 9 years ago.
I have a textfield that inputs date in this format: yyyy-mm-dd, how can I add a day to that users input? I have the following code but it doesnt work...
users_date = document.getElementById('users_date').value;
var date = new Date(users_date);
var next_date = new Date();
next_date .setDate(date.getDate()+1);
document.getElementById('next_date').value = next_date;
The first problem is the format of the date in the second is like 'Mon Aug 05 2013 16:24:40 GMT-0500 (Hora est. Pacífico, Sudamérica)'
The second problem is that when the user input the fist day of the month like '2013-01-01' or '2013-08-01' it displays 'Sun Sep 01 2013 16:26:06 GMT-0500 (Hora est. Pacífico, Sudamérica)' ALWAYS
For example if user inputs 2013-01-01 I want another textfield to be 2013-01-02 or 2013-08-31 it displays 2013-09-01, how can I do that?
Thanks!!
ITS NOT DUPLICATE BECAUSE THE OTHER POST DOESN'T FORMAT THE DATE!!!!
Prior to ES5 there was no standard for parsing dates. Now there is a format that is a version of ISO8601, however it isn't supported by all browsers in use and is not typically used for user input.
Normally a format is requested or a "date picker" used that returns a specific format. From there, it's quite simple to parse the string to create a Date object:
// s is date string in d/m/y format
function stringToDate(s) {
var b = s.split(/\D/);
return new Date(b[2], --b[1], b[0]);
}
For ISO8601 format (y-m-d), just change the order of the parts:
// s is date string in y/m/d format
function isoStringToDate(s) {
var b = s.split(/\D/);
return new Date(b[0], --b[1], b[2]);
}
To add one day to a Date object, just add one day:
var now = new Date();
var tomorrow = now.setDate(now.getDate() + 1);
This should work:
var date = new Date(document.getElementById('users_date').value);
var next_date = new Date(date.getTime() + 24*60*60*1000); // adding a day
document.getElementById('next_date').value = next_date.getFullYear() + "-" +
(next_date.getMonth()++) + "-" + next_date.getDate();
Please, note that Date#getMonth() is zero-based. Hence, the increment.
I have been using
timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toString());
And it will output for example:
Tue Jul 6 08:47:00 CDT 2010
//24 hour time
Screen real estate is prime, so I would like to take up less space with the date and output:
mm/dd/yy hh:mm
//also 24 hour time
Just add an extra method to the Date object, so you can reuse it as much as you want. First, we need to define a helper function, String.padLeft:
String.prototype.padLeft = function (length, character) {
return new Array(length - this.length + 1).join(character || ' ') + this;
};
After this, we define Date.toFormattedString:
Date.prototype.toFormattedString = function () {
return [String(this.getMonth()+1).padLeft(2, '0'),
String(this.getDate()).padLeft(2, '0'),
String(this.getFullYear()).substr(2, 2)].join("/") + " " +
[String(this.getHours()).padLeft(2, '0'),
String(this.getMinutes()).padLeft(2, '0')].join(":");
};
Now you can simply use this method like any other method of the Date object:
var timeStamp = new Date(unixTime*1000);
document.write(timeStamp.toFormattedString());
But please bear in mind that this kind of formatting can be confusing. E.g., when issuing
new Date().toFormattedString()
the function returns 07/06/10 22:05 at the moment. For me, this is more like June 7th than July 6th.
EDIT: This only works if the year can be represented using a four-digit number. After December 31st, 9999, this will malfunction and you'll have to adjust the code.
I have a date like this Monday, January 9, 2010
I now want to convert it to
1/9/2010 mm/dd/yyyy
I tried to do this
var startDate = "Monday, January 9, 2010";
var convertedStartDate = new Date(startDate);
var month = convertedStartDate.getMonth() + 1
var day = convertedStartDate.getDay();
var year = convertedStartDate.getFullYear();
var shortStartDate = month + "/" + day + "/" + year;
However it must be thinking the date is in a different format since day returns 1 instead of 9.
Here you go:
(new Date()).toLocaleDateString('en-US');
That's it !!
you can use it on any date object
let's say.. you have an object called "currentDate"
var currentDate = new Date(); //use your date here
currentDate.toLocaleDateString('en-US'); // "en-US" gives date in US Format - mm/dd/yy
(or)
If you want it in local format then
currentDate.toLocaleDateString(); // gives date in local Format
The getDay() method returns a number to indicate the day in week (0=Sun, 1=Mon, ... 6=Sat). Use getDate() to return a number for the day in month:
var day = convertedStartDate.getDate();
If you like, you can try to add a custom format function to the prototype of the Date object:
Date.prototype.formatMMDDYYYY = function(){
return (this.getMonth() + 1) +
"/" + this.getDate() +
"/" + this.getFullYear();
}
After doing this, you can call formatMMDDYYY() on any instance of the Date object. Of course, this is just a very specific example, and if you really need it, you can write a generic formatting function that would do this based on a formatting string, kinda like java's SimpleDateeFormat (http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html)
(tangent: the Date object always confuses me... getYear() vs getFullYear(), getDate() vs getDay(), getDate() ranges from 1..31, but getMonth() from 0..11
It's a mess, and I always need to take a peek. http://www.w3schools.com/jsref/jsref_obj_date.asp)
Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:
new Date(dateString).toLocaleDateString('en-US', {
day: '2-digit',
month: '2-digit',
year: 'numeric',
})
Alternative: We can get similar behavior using Intl.DateTimeFormat which has decent browser support. Similar to toLocaleDateString(), we can pass an object with options:
const date = new Date('Dec 2, 2021') // Thu Dec 16 2021 15:49:39 GMT-0600
const options = {
day: '2-digit',
month: '2-digit',
year: 'numeric',
}
new Intl.DateTimeFormat('en-US', options).format(date) // '12/02/2021'
var d = new Date("Wed Mar 25 2015 05:30:00 GMT+0530 (India Standard Time)");
document.getElementById("demo").innerHTML = d.toLocaleDateString();
date.toLocaleDateString('en-US') works great. Here's some more information on it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
I wanted the date to be shown in the type='time' field.
The normal conversion skips the zeros and the form field does not show the value and puts forth an error in the console saying the format needs to be yyyy-mm-dd.
Hence I added a small statement (check)?(true):(false) as follows:
makeShortDate=(date)=>{
yy=date.getFullYear()
mm=date.getMonth()
dd=date.getDate()
shortDate=`${yy}-${(mm<10)?0:''}${mm+1}-${(dd<10)?0:''}${dd}`;
return shortDate;
}
Although this question posted long long time ago, the proper way to do this is:
Intl.DateTimeFormat("en").format(new Date())
Any way, the Intl (international) object has many options you can pass to like to enforce tow digits etc.
You all can look at it here
I was able to do that with :
var dateTest = new Date("04/04/2013");
dateTest.toLocaleString().substring(0,dateTest.toLocaleString().indexOf(' '))
the 04/04/2013 is just for testing, replace with your Date Object.
You could do this pretty easily with my date-shortcode package:
const dateShortcode = require('date-shortcode')
var startDate = 'Monday, January 9, 2010'
dateShortcode.parse('{M/D/YYYY}', startDate)
//=> '1/9/2010'
Try this:
new Date().toLocaleFormat("%x");