среда, 23 декабря 2015 г.

Java: operations with dates (+Java Date and Calendar examples)

DateFormat and SimpleDateFormat Examples

Version 1.1 of Java introduced the java.text package, which included utility classes for parsing and formatting numbers and dates, along with utility classes for building other kinds of parsers.
Default date formats
The java.text.DateFormat class, and its concrete subclass java.text.SimpleDateFormat, provide a convenient way to convert strings with date and/or time info to and from java.util.Date objects. Figure 1 shows an example of using default DateFormat objects to format a date in a variety of ways:

import java.text.DateFormat;
import java.util.Date;

public class DateFormatExample1 {

    public static void main(String[] args) {
        // Make a new Date object. It will be initialized to the current time.
        Date now = new Date();

        // See what toString() returns
        System.out.println(" 1. " + now.toString());

        // Next, try the default DateFormat
        System.out.println(" 2. " + DateFormat.getInstance().format(now));

        // And the default time and date-time DateFormats
        System.out.println(" 3. " + DateFormat.getTimeInstance().format(now));
        System.out.println(" 4. " + 
            DateFormat.getDateTimeInstance().format(now));

        // Next, try the short, medium and long variants of the 
        // default time format 
        System.out.println(" 5. " + 
            DateFormat.getTimeInstance(DateFormat.SHORT).format(now));
        System.out.println(" 6. " + 
            DateFormat.getTimeInstance(DateFormat.MEDIUM).format(now));
        System.out.println(" 7. " + 
            DateFormat.getTimeInstance(DateFormat.LONG).format(now));

        // For the default date-time format, the length of both the
        // date and time elements can be specified. Here are some examples:
        System.out.println(" 8. " + DateFormat.getDateTimeInstance(
            DateFormat.SHORT, DateFormat.SHORT).format(now));
        System.out.println(" 9. " + DateFormat.getDateTimeInstance(
            DateFormat.MEDIUM, DateFormat.SHORT).format(now));
        System.out.println("10. " + DateFormat.getDateTimeInstance(
            DateFormat.LONG, DateFormat.LONG).format(now));
    }
}


Figure 1. Using default DateFormat objects to format a Date object.
When you run this class, you will see output that looks something like that shown in Figure 2.

> java DateFormatExample1
 1. Tue Nov 04 20:14:11 EST 2003
 2. 11/4/03 8:14 PM
 3. 8:14:11 PM
 4. Nov 4, 2003 8:14:11 PM
 5. 8:14 PM
 6. 8:14:11 PM
 7. 8:14:11 PM EST
 8. 11/4/03 8:14 PM
 9. Nov 4, 2003 8:14 PM
10. November 4, 2003 8:14:11 PM EST


Figure 2. Output from example in Figure 1
Default DateFormat objects retrieved from the static getInstance(), getTimeInstance(), and getDateTimeInstance() methods can also be used for parsing String objects to produce Date objects. Figure 3 shows a simple example of this.

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;

public class DateFormatExample2 {

    public static void main(String[] args) {
        // Make a String that has a date in it, with MEDIUM date format
        // and SHORT time format.
        String dateString = "Nov 4, 2003 8:14 PM";

        // Get the default MEDIUM/SHORT DateFormat
        DateFormat format = 
            DateFormat.getDateTimeInstance(
            DateFormat.MEDIUM, DateFormat.SHORT);

        // Parse the date
        try {
            Date date = format.parse(dateString);
            System.out.println("Original string: " + dateString);
            System.out.println("Parsed date    : " + 
                 date.toString());
        }
        catch(ParseException pe) {
            System.out.println("ERROR: could not parse date in string \"" +
                dateString + "\"");
        }
    }
}


Figure 3. Using default DateFormat objects to parse a String
The result is shown in Figure 4. Note that since the string version of the date did not contain timezone or seconds, the timezone is set to the default timezone (EST, in this case) and the seconds are set to zero.

> java DateFormatExample2
Original string: Nov 4, 2003 8:14 PM
Parsed date    : Tue Nov 04 20:14:00 EST 2003


Figure 4. Parsing a date string
The parse method throws an exception if a date matching the format cannot be parsed. In the code shown in Figure 3, the string matches the format exactly. To see what happens when a bad string is encountered, the class in Figure 5 reads and attempts to parse input until a blank line (or a Control-D) is entered.

import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class DateFormatExample3 {

    public static void main(String[] args) {
        // Get the default MEDIUM/SHORT DateFormat
        DateFormat format = 
            DateFormat.getDateTimeInstance(DateFormat.MEDIUM, 
            DateFormat.SHORT);

        // Read and parse input, stopping on a blank input line
        BufferedReader reader = 
            new BufferedReader(new InputStreamReader(System.in));
        try {
            System.out.print("ENTER DATE STRING: ");
            String dateString = reader.readLine();

            while ((dateString != null) && (dateString.length() > 0)) {
                // Parse the date
                try {
                    Date date = format.parse(dateString);
                    System.out.println("Original string: " + dateString);
                    System.out.println("Parsed date    : " + 
                        date.toString());
                    System.out.println(); // Skip a line
                }
                catch(ParseException pe) {
                    System.out.println(
                        "ERROR: could not parse date in string \"" +
                        dateString + "\"");
                }

                // Read another string
                System.out.print("ENTER DATE STRING: ");
                dateString = reader.readLine();
            }
        }
        catch(IOException ioe) {
            System.out.println("I/O Exception: " + ioe);
        }
    }
}


Figure 5. Example of parsing dates entered on the command line
Figure 6 shows an example of running this class and entering several date strings. (Text entered is shown in italics.)

> java DateFormatExample3
ENTER DATE STRING: Nov 4, 2003 8:14 PM
Original string: Nov 4, 2003 8:14 PM
Parsed date    : Tue Nov 04 20:14:00 EST 2003

ENTER DATE STRING: Nov 4, 2003 8:14
ERROR: could not parse date in string "Nov 4, 2003 8:14 "

ENTER DATE STRING: Nov 4, 2003 8:14 AM
Original string: Nov 4, 2003 8:14 AM
Parsed date    : Tue Nov 04 08:14:00 EST 2003

ENTER DATE STRING: November 4, 2003 8:14 AM
Original string: November 4, 2003 8:14 AM
Parsed date    : Tue Nov 04 08:14:00 EST 2003

ENTER DATE STRING: Nov 4, 2003 20:14 PM
Original string: Nov 4, 2003 20:14 PM
Parsed date    : Wed Nov 05 08:14:00 EST 2003

ENTER DATE STRING: Nov 4, 2003 20:14  
ERROR: could not parse date in string "Nov 4, 2003 20:14"

ENTER DATE STRING: 


Figure 6. Parsing a variety of date strings
Note that the default parser is somewhat flexible. It recognizes a long version of the month name (“November” instead of “Nov”), but does not recognize the two dates shown in red, both of which are missing AM or PM. Furthermore, it produces possibly unexpected results when the time “20:14 PM” is entered: The parsed date is 8:14 the next morning.
DateFormat actually gives you a small amount of control over leniency in parsing. The default DateFormat instances are lenient by default, but invoking format.setLenient(false); in the example in Figure 5 would cause the “20:14 PM” example (in Figure 6) to fail, though it will still accept “November” or “Nov”.
Using SimpleDateFormat for custom date formatting and parsing
The default DateFormat instances returned by the static methods in the DateFormat class may be sufficient for many purposes, but clearly do not cover all possible valid or useful formats for dates. For example, notice that in Figure 2, none of the DateFormat-generated strings (numbers 2 – 9) match the format of the output of the Date class’s toString() method. This means that you cannot use the default DateFormat instances to parse the output of toString(), something that might be useful for things like parsing log data.
The SimpleDateFormat lets you build custom formats. Dates are constructed with a string that specifies a pattern for the dates to be formatted and/or parsed. From the SimpleDateFormat JavaDocs, the characters in Figure 7 can be used in date formats. Where appropriate, 4 or more of the character will be interpreted to mean that the long format of the element should be used, while fewer than 4 mean that a short format should be used.



SymbolMeaningTypeExample
GEraText“GG” -> “AD”
yYearNumber“yy” -> “03″
“yyyy” -> “2003″
MMonthText or Number“M” -> “7″
“M” -> “12″
“MM” -> “07″
“MMM” -> “Jul”
“MMMM” -> “December”
dDay in monthNumber“d” -> “3″
“dd” -> “03″
hHour (1-12, AM/PM)Number“h” -> “3″
“hh” -> “03″
HHour (0-23)Number“H” -> “15″
“HH” -> “15″
kHour (1-24)Number“k” -> “3″
“kk” -> “03″
KHour (0-11 AM/PM)Number“K” -> “15″
“KK” -> “15″
mMinuteNumber“m” -> “7″
“m” -> “15″
“mm” -> “15″
sSecondNumber“s” -> “15″
“ss” -> “15″
SMillisecond (0-999)Number“SSS” -> “007″
EDay in weekText“EEE” -> “Tue”
“EEEE” -> “Tuesday”
DDay in year (1-365 or 1-364)Number“D” -> “65″
“DDD” -> “065″
FDay of week in month (1-5)Number“F” -> “1″
wWeek in year (1-53)Number“w” -> “7″
WWeek in month (1-5)Number“W” -> “3″
aAM/PMText“a” -> “AM”
“aa” -> “AM”
zTime zoneText“z” -> “EST”
“zzz” -> “EST”
“zzzz” -> “Eastern Standard Time”
Excape for textDelimiter“‘hour’ h” -> “hour 9″
Single quoteLiteral“ss”SSS” -> “45’876″


Figure 7. Syntax elements for SimpleDateFormat
Note that you will generally never want to use single-digit minutes, seconds, or milliseconds, even though these are supported by SimpleDateFormat (“m”, “s”, “S”).
Using the syntax from Figure 7, we can now make a SimpleDateFormat that can read the output of Date.toString(). Figure 8 shows an example this:


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;

public class DateFormatExample4 {

    public static void main(String[] args) {
        // Make a new Date object. It will be initialized to the 
        // current time.
        Date now = new Date();

        // Print the result of toString()
        String dateString = now.toString();
        System.out.println(" 1. " + dateString);

        // Make a SimpleDateFormat for toString()'s output. This
        // has short (text) date, a space, short (text) month, a space,
        // 2-digit date, a space, hour (0-23), minute, second, a space,
        // short timezone, a final space, and a long year.
        SimpleDateFormat format = 
            new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

        // See if we can parse the output of Date.toString()
        try {
            Date parsed = format.parse(dateString);
            System.out.println(" 2. " + parsed.toString());
        }
        catch(ParseException pe) {
            System.out.println("ERROR: Cannot parse \"" + dateString + "\"");
        }

        // Print the result of formatting the now Date to see if the result
        // is the same as the output of toString()
        System.out.println(" 3. " + format.format(now));
    }
}
The output shows three identical strings:
> java DateFormatExample4
 1. Tue Nov 04 21:53:43 EST 2003
 2. Tue Nov 04 21:53:43 EST 2003
 3. Tue Nov 04 21:53:43 EST 2003


Figure 8. A parser for Date.toString() output

среда, 9 декабря 2015 г.

SQL. Dates and formats

В случае использования разных форматов в выводе информации для пользователя и в самой БД, могут возникать ситуации, когда с формированный запрос не соответствует формату.
Тогда необходимо использовать ключевое слово для преобразования формата в необходимый вид:

alter session set nls_date_format = 'YYYY-MM-DD';
SELECT * FROM CHANNEL_DETAILS
WHERE CALLSIGN IN('Audio','DTV')
AND ((CHANNEL_STATE='ACT') OR (CHANNEL_STATE='RDY') OR (CHANNEL_STATE='NEW'))
AND CH_START<=to_date('2015-12-30')
AND CH_END>=to_date('2015-12-04');

пятница, 4 декабря 2015 г.

Unix: Emptying the buffers cache

Practice: 
echo 1 > /proc/sys/vm/drop_caches

Additional info:

If you ever want to empty it you can use this chain of commands.
# free && sync && echo 3 > /proc/sys/vm/drop_caches && free

             total       used       free     shared    buffers     cached
Mem:       1018916     980832      38084          0      46924     355764
-/+ buffers/cache:     578144     440772
Swap:      2064376        128    2064248
             total       used       free     shared    buffers     cached
Mem:       1018916     685008     333908          0        224     108252
-/+ buffers/cache:     576532     442384
Swap:      2064376        128    2064248
You can signal the Linux Kernel to drop various aspects of cached items by changing the numeric argument to the above command.
  • To free pagecache:
    # echo 1 > /proc/sys/vm/drop_caches
    
  • To free dentries and inodes:
    # echo 2 > /proc/sys/vm/drop_caches
    
  • To free pagecache, dentries and inodes:
    # echo 3 > /proc/sys/vm/drop_caches
    
The above are meant to be run as root. If you're trying to do them using sudo then you'll need to change the syntax slightly to something like these:
$ sudo sh -c 'echo 1 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 2 >/proc/sys/vm/drop_caches'
$ sudo sh -c 'echo 3 >/proc/sys/vm/drop_caches'
NOTE: There's a more esoteric version of the above command if you're into that:
$ echo "echo 1 > /proc/sys/vm/drop_caches" | sudo sh
Why the change in syntax? The /bin/echo program is running as root, because of sudo, but the shell that's redirecting echo's output to the root-only file is still running as you. Your current shell does the redirection before sudo starts.

Seeing what's in the buffers and cache

Take a look at linux-ftools if you'd like to analyze the contents of the buffers & cache. Specifically if you'd like to see what files are currently being cached.

fincore

With this tool you can see what files are being cached within a give directory.
fincore [options] files...

  --pages=false      Do not print pages
  --summarize        When comparing multiple files, print a summary report
  --only-cached      Only print stats for files that are actually in cache.
For example, /var/lib/mysql/blogindex:
root@xxxxxx:/var/lib/mysql/blogindex# fincore --pages=false --summarize --only-cached * 
stats for CLUSTER_LOG_2010_05_21.MYI: file size=93840384 , total pages=22910 , cached pages=1 , cached size=4096, cached perc=0.004365 
stats for CLUSTER_LOG_2010_05_22.MYI: file size=417792 , total pages=102 , cached pages=1 , cached size=4096, cached perc=0.980392 
stats for CLUSTER_LOG_2010_05_23.MYI: file size=826368 , total pages=201 , cached pages=1 , cached size=4096, cached perc=0.497512 
stats for CLUSTER_LOG_2010_05_24.MYI: file size=192512 , total pages=47 , cached pages=1 , cached size=4096, cached perc=2.127660 
stats for CLUSTER_LOG_2010_06_03.MYI: file size=345088 , total pages=84 , cached pages=43 , cached size=176128, cached perc=51.190476 
stats for CLUSTER_LOG_2010_06_04.MYD: file size=1478552 , total pages=360 , cached pages=97 , cached size=397312, cached perc=26.944444 
stats for CLUSTER_LOG_2010_06_04.MYI: file size=205824 , total pages=50 , cached pages=29 , cached size=118784, cached perc=58.000000 
stats for COMMENT_CONTENT_2010_06_03.MYI: file size=100051968 , total pages=24426 , cached pages=10253 , cached size=41996288, cached perc=41.975764 
stats for COMMENT_CONTENT_2010_06_04.MYD: file size=716369644 , total pages=174894 , cached pages=79821 , cached size=326946816, cached perc=45.639645 
stats for COMMENT_CONTENT_2010_06_04.MYI: file size=56832000 , total pages=13875 , cached pages=5365 , cached size=21975040, cached perc=38.666667 
stats for FEED_CONTENT_2010_06_03.MYI: file size=1001518080 , total pages=244511 , cached pages=98975 , cached size=405401600, cached perc=40.478751 
stats for FEED_CONTENT_2010_06_04.MYD: file size=9206385684 , total pages=2247652 , cached pages=1018661 , cached size=4172435456, cached perc=45.321117 
stats for FEED_CONTENT_2010_06_04.MYI: file size=638005248 , total pages=155763 , cached pages=52912 , cached size=216727552, cached perc=33.969556 
stats for FEED_CONTENT_2010_06_04.frm: file size=9840 , total pages=2 , cached pages=3 , cached size=12288, cached perc=150.000000 
stats for PERMALINK_CONTENT_2010_06_03.MYI: file size=1035290624 , total pages=252756 , cached pages=108563 , cached size=444674048, cached perc=42.951700 
stats for PERMALINK_CONTENT_2010_06_04.MYD: file size=55619712720 , total pages=13579031 , cached pages=6590322 , cached size=26993958912, cached perc=48.533080 
stats for PERMALINK_CONTENT_2010_06_04.MYI: file size=659397632 , total pages=160985 , cached pages=54304 , cached size=222429184, cached perc=33.732335 
stats for PERMALINK_CONTENT_2010_06_04.frm: file size=10156 , total pages=2 , cached pages=3 , cached size=12288, cached perc=150.000000 
---
total cached size: 32847278080
With the above output you can see that there are several *.MYD, *.MYI, and *.frm files that are currently being cached.

Swap

If you want to clear out your swap you can use the following commands.
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7298164     689328          0      30416     457936
-/+ buffers/cache:    6809812    1177680
Swap:      5963772     609452    5354320
Then use this command to disable swap:
$ swapoff -a
You can confirm that it's now empty:
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7777912     209580          0      39332     489864
-/+ buffers/cache:    7248716     738776
Swap:            0          0          0
And to re-enable it:
$ swapon -a
And now reconfirm with free:
$ free
             total       used       free     shared    buffers     cached
Mem:       7987492    7785572     201920          0      41556     491508
-/+ buffers/cache:    7252508     734984
Swap:      5963772          0    5963772 
 
 http://unix.stackexchange.com/questions/87908/how-do-you-empty-the-buffers-and-cache-on-a-linux-system

SEO: Эксперимент: как Яндекс и Google учитывают ключевые слова в URL

Эксперимент: как Яндекс и Google учитывают ключевые слова в URL Эксперимент: как Яндекс и Google учитывают ключевые слова в URL Дата пу...