Parse month text using parseDate utility method - javascript

I'm having trouble parsing a month year string into a date when using the jquery ui 's utility method $.datepicker.parseDate(format, string, settings). ( https://api.jqueryui.com/datepicker/ )
When I use it like
var dt = $.datepicker.parseDate('MM yy', 'January 2011');
I expect it to return a date which equals new Date(2011,00,1), but instead I get an invalid date. Does jqueryui's parseDate support full date string parsing? I can't really find any good docs on this. I expected it to support the full month parsing because the datepicker is able to display it in full month format. I've set up a fiddle* to demonstrate my problem. The core code from the fiddle is below.
*http://jsfiddle.net/mouseoctopus/fvrpG/
var text = $('#dateText').val();
var format = $('#dateFormat').val();
$('#instructions').text('Parse the date [' + text + '] using the format [' + format +']');
try{
var dt = $.datepicker.parseDate(format,text);
$('#result').text(dt);
}catch(exception){ }
So my question is.. it possible to parse a full month text using the parseDate?

I can't speak for jQuery parseDate, but you can use a native JavaScript Date.parse with the full month. The JavaScript function requires a full date though, so you'll need to add 1 in front of the date. It returns a timestamp which you can use it to create a new date.
You can find complete documentation at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
Example
alert(new Date(Date.parse('1 January 2011')));

Related

Date(string) shows different date and time using toLocaleString

I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
See fiddle: https://jsfiddle.net/f1kLpfgd/
Javascript Date string constructing wrong date explains the wrong date with time zones. I have a different problem, as even minutes and seconds differ from my input. The solution using the new Date(1822, 0, 1, 0, 0, 0, 0) constructor does not work for me, as the result is 31.12.1821, 23:53:28.
Is it because the year is before 1901? But even 1899 works perfectly fine...
Update
For the formatting example custom VS toLocaleString, see updated fiddle: https://jsfiddle.net/f1kLpfgd/8/
If you don't want to use some library like date-fns , moment.js ...
To get the desired you could try like:
var dateString = "1822-01-01 00:00:00";
var d = new Date(dateString);
var formatted = d.getDate() +'.'+
(d.getMonth()+1) +'.'+
d.getFullYear() +', '+
dateString.substr(11);
console.log(formatted);
I want to turn the string 1822-01-01 00:00:00 into a date by:
var d= new Date("1822-01-01 00:00:00");
What I expect using d.toLocaleString() is 1.1.1822, 00:00:00, but what I get is 31.12.1821, 23:53:28.
Do not use the built-in parser for non-standard strings as whatever you get is implementation dependent and likely not what you expect in at least some hosts. In Safari, d will be an invalid date.
The format returned by toLocaleString is implementation dependent and varies between browsers. For me, new Date().toLocaleString() returns "9/21/2017, 9:48:49 AM", which is not consistent with the format typically used either in my locality or by users of the language I speak.
If you just want to reformat the string, see Reformat string containing date with Javascript.
If you want to know how to parse the string correctly, see Why does Date.parse
give incorrect results?
If you want to format a Date, see Where can I find documentation on formatting a date in JavaScript?

Unable to set Date Format with Javascript

I am trying to collect a date from text boxes and then do a comparison on them. I am entering the dates in dd-MM-yyyy format, however when the comparison is running its running is in a MM-dd-yyyy format.
my fiddle is here
in my live application I am using a bootstrap datepicker to enter the date so the date entered will always be the correct format.
Ive looked here at W3 Schools and I have also tried looking at
var dt1 = d1.split(/\-|\s/)
var dt2 = d2.split(/\-|\s/)
dat1 = new Date(dt1);
dat2 = new Date(dt2);
dat1.format("dd-MM-yyyy")
but this also fails.
Any and all help very much appreciated.
thanks
Use the getTime() method if you want to make comparison on dates :
if(dat1.getTime() > dat2.getTime()) { ... }
On your example : https://jsfiddle.net/3ut8a7zj/1/

No format support in Date object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Extending JavaScript's Date.parse to allow for DD/MM/YYYY (non-US formatted dates)?
Convert dd-mm-yyyy string to date
Entered a date in textbox, for example: 05/09/1985, and I wanted to convert it to 05-Sep-1985 (dd-MMM-yyyy) format. How would I achieve this? Note that the source format may be dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format.
Code Snippet:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val());
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
This code returns 09-May-1985 but I want 05-Sep-1985. Thanks.
You might want to use helper library like http://momentjs.com/ which wraps the native javascript date object for easier manipulations
Then you can do things like:
var day = moment("12-25-1995", "MM-DD-YYYY");
or
var day = moment("25/12/1995", "DD/MM/YYYY");
then operate on the date
day.add('days', 7)
and to get the native javascript date
day.toDate();
Update
Below you've said:
Sorry, i can't predict date format before, it should be like dd-mm-yyyy or dd/mm/yyyy or dd-mmm-yyyy format finally i wanted to convert all this format to dd-MMM-yyyy format.
That completely changes the question. It'll be much more complex if you can't control the format. There is nothing built into JavaScript that will let you specify a date format. Officially, the only date format supported by JavaScript is a simplified version of ISO-8601: yyyy-mm-dd, although in practice almost all browsers also support yyyy/mm/dd as well. But other than that, you have to write the code yourself or (and this makes much more sense) use a good library. I'd probably use a library like moment.js or DateJS (although DateJS hasn't been maintained in years).
Original answer:
If the format is always dd/mm/yyyy, then this is trivial:
var parts = str.split("/");
var dt = new Date(parseInt(parts[2], 10),
parseInt(parts[1], 10) - 1,
parseInt(parts[0], 10));
split splits a string on the given delimiter. Then we use parseInt to convert the strings into numbers, and we use the new Date constructor to build a Date from those parts: The third part will be the year, the second part the month, and the first part the day. Date uses zero-based month numbers, and so we have to subtract one from the month number.
Date.parse recognizes only specific formats, and you don't have the option of telling it what your input format is. In this case it thinks that the input is in the format mm/dd/yyyy, so the result is wrong.
To fix this, you need either to parse the input yourself (e.g. with String.split) and then manually construct a Date object, or use a more full-featured library such as datejs.
Example for manual parsing:
var input = $('#' + controlName).val();
var parts = str.split("/");
var d1 = new Date(Number(parts[2]), Number(parts[1]) - 1, Number(parts[0]));
Example using date.js:
var input = $('#' + controlName).val();
var d1 = Date.parseExact(input, "d/M/yyyy");
Try this:
function GetDateFormat(controlName) {
if ($('#' + controlName).val() != "") {
var d1 = Date.parse($('#' + controlName).val().toString().replace(/([0-9]+)\/([0-9]+)/,'$2/$1'));
if (d1 == null) {
alert('Date Invalid.');
$('#' + controlName).val("");
}
var array = d1.toString('dd-MMM-yyyy');
$('#' + controlName).val(array);
}
}
The RegExp replace .replace(/([0-9]+)\/([0-9]+)/,'$2/$1') change day/month position.
See this http://blog.stevenlevithan.com/archives/date-time-format
you can do anything with date.
file : http://stevenlevithan.com/assets/misc/date.format.js
add this to your html code using script tag and to use you can use it as :
var now = new Date();
now.format("m/dd/yy");
// Returns, e.g., 6/09/07

moment js cannot change date string to new format

I have the following HTML:
<strong id="ut-open-date">27/06/2014</strong>
and I want to read the text/innerhtml and convert its format to "YYYY-MM-DD" so I can insert it into MySQL table. I am using the moment.js library and my code is below:
var CreateDate = moment(jQuery('#ut-open-date').html()).format("DD/MM/YYYY");
CreateDate = moment(CreateDate).format("YYYY-MM-DD");
But the code changes 27/06/2014 to 2016-06-03 and I cannot work out why.
I also tried this code with the same result.
var CreateDate = moment(jQuery('#ut-open-date').html()).format("YYYY-MM-DD");
Any help is appreciated.
If we break down your code step by step you can see where it is going wrong:
var CreateDate = moment(jQuery('#ut-open-date').html())
This part uses the default constructor to try to parse the date, this is unreliable at best and has been deprecated. So moment is trying to guess what the date format is here.
.format("DD/MM/YYYY");
This is taking what ever was read in step 1 and trying to turn it into a string with the format of DD/MM/YYYY
CreateDate = moment(CreateDate)
Now you are parsing again without specifying the format so moment is doing it's best to guess
.format("YYYY-MM-DD");
Now you have told it to turn whatever it guessed the date to be into a string with the format YYYY-MM-DD
Do this instead:
var CreateDate = moment(jQuery('#ut-open-date').html(), 'DD/MM/YYYY').format('YYYY-MM-DD');
The moment(dateString) form is deprecated you should use the form moment(dateString, expectedFormat) instead.
See moment documentation here: http://momentjs.com/docs/#/parsing/string-format/
Thanks to athms for link
The problem is you need to tell moment.js what format for date string you want parse by specifying second parameter. See all the supported format. If your format is not listed (See the Open Issue for NON-ISO strings), you need to specify the date format parameter.
moment( jQuery('#ut-open-date').html(), "DD/MM/YYYY" )
DEMO
I solved it by using split as follows:
var CreateDate = jQuery('#ut-open-date').text();
var DateArray = CreateDate.split('/');
CreateDate = DateArray[2] + '-' + DateArray[1] + '-' + DateArray[0];

Is there a built-in JavaScript function to process a time string?

To make a time like "2009-05-02 00:00:00" to "2009-05-02".
I know I can achieve this by a regular expression, but is there a built-in function that can do this?
There's no built-in date function that can do that. As a matter of fact if you create a new Date object in JavaScript with that date format, you get an Invalid Date Error.
You are correct in using a regular expression or string manipulation in this case.
Here's a list of all the JavaScript Date Functions.
To simply get the date portion of the string and display it without converting into a Date Object. You can simply do this:
var dateString = "2009-05-02 00:00:00"
alert(dateString.substring(0,10)); // Will show "2009-05-02"
To convert this string into a proper JavaScript Date Object, you can use this snippet:
function sqlTimeStampToDate(timestamp) {
// This function parses SQL datetime string and returns a JavaScript Date object
// The input has to be in this format: 2007-06-05 15:26:02
var regex=/^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
var parts=timestamp.replace(regex,"$1 $2 $3 $4 $5 $6").split(' ');
return new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]);
}
The format will be "ddd MMM dd YYYY hh:mm:ss" + TimeOffSet, but you will be able to use any of the standard JavaScript date functions.
See below for two simple methods to get a date format of "2009-05-02", from the initial format, that is "2009-05-02 00:00:00".
<script type="text/javascript">
var mydate, newdate1, newdate2;
mydate = "2009-05-02 00:00:00";
newdate1 = (mydate.split(/ /))[0];
alert('newdate 1: ' + newdate1);
newdate2 = mydate.substr(0,10);
alert('newdate 2: ' + newdate2);
</script>
You might find this helpful:
Return today's date and time
How to use the Date() method to get today's date.
getTime()
Use getTime() to calculate the years since 1970.
setFullYear()
How to use setFullYear() to set a specific date.
toUTCString()
How to use toUTCString() to convert today's date (according to UTC) to a string.
getDay()
Use getDay() and an array to write a weekday, and not just a number.
This is copy-paste from www.w3schools.com since I can't post a link to it...
Or just search Google for "JavaScript date function" or related. Regular expressions are used to match specific parts of strings, which is useful in searching, extraction and replacement, not really anything that would help you with formatting a date.

Categories

Resources