开发者

Questions about javascript dates

开发者 https://www.devze.com 2022-12-15 19:06 出处:网络
I have 2 questions about dates. The first one is how can I get the \"AM/PM\" from a date in Javascript?

I have 2 questions about dates.

The first one is how can I get the "AM/PM" from a date in Javascript?

the second question is say I have this code

    var convertedStartDate = new Date(dueDate);
    var month = convertedStartDate.getMonth() + 1;
    var day = convertedStartDate.getDate();
    var year = convertedStartDate.getFullYear();
     var shortDueDate = month + "/" + day + "/" + year;

Now as you can see I want always this format mm/dd/yyyy

So I am wondering if say dueDate is 1/9/2010 (mm/dd/yyyy) but the person entered it in as dd/mm/yyyy(some other format version of date).

would开发者_开发百科

month = 1 day = 9 year = 2010

Or do I have to tell it somehow to always convert into mm/dd/yyyy? Or does it do is own format so that it always would get the right order? Ie it does not matter what order they put the date in it would always get 9 as the day.


Here, give this a try:

now = new Date();

hour = now.getHours();
var tag = "";

if (hour >= 12) {
  tag = "pm";
} else {
  tag = "am";
}

As for the second part of your question, I'd just make those parts of the form separate fields, there really is no way otherwise. You're just going to have to write some hints into your form.


You need to always turn/convert whatever the user entered into a Javascript Date object. Remember - Javascript is local to the client's computer... a person in the USA will have different format settings than a person in the UK or China.

To keep things simple... suggest or present a hint near the input textbox the desired input format. Then, validate against that format using a Regex. This way you are almost guaranteed to get the desired date... well... unless the user has Javascript disabled. LOL... in that case... you need to convert on the server-side (you should always be doing this anyway).


To get the AM/PM of a time found some old code I wrote a long time ago. See the (remove am/pm) here you can replace it with a get using the substring.

function ValidateAdvancedTime(time, formatType){
  time = time.replace(".", ":");
  var newTime = time.substring(0, (time.indexOf(":") + 3)); // Strip out the seconds
  var status = ValidateTime(newTime, formatType);

  if(status == false) 
    return false;

  var seconds = time.substring(time.indexOf(":") + 4, time.length);
  if(seconds.length > 2) 
    **seconds = seconds.substring(0, 2);                      // Remove any AM/PM afterwards**

  if(!isNaN(seconds)) {                                         // Make sure its a number and it's between 0 and 59
    if((seconds <= 59) && (seconds >= 0)) 
        return true;
  }
  return false; 

}

As far as the dates go I've never had any problems storing 1/9/2010 or 01/09/2010 in the database.

0

精彩评论

暂无评论...
验证码 换一张
取 消